ahmeix0l
asked on
Using VAriable in replace() using javascript
Can I use variable in replace function for old and new string? I know that old new string can be variable. How abt old string? Replace all "The" to "Ze" using variable not literals.
Thanks
Thanks
<html>
<body>
<script type="text/javascript">
var str = "The Lord of the Rings: The Fellowship of the Ring";
var news = "ze";
var old = "The"
var result = str.replace(/old/gi,news);
document.write(result);
</script>
</body>
</html>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I think str.replace(old,news); also does the job,
Thanks dude.
Thanks dude.
Not completely since you miss the gi.
Ps: my name is Michel :)
Ps: my name is Michel :)
See:
<html>
<body>
<script type="text/javascript">
var str = "The Lord of the Rings: The Fellowship of the Ring";
var news = "ze";
var old = "The"
var reg = new RegExp(old,"gi")
var result = str.replace(reg,news);
document.write(result);
var result = str.replace(old,news);
document.write('<hr>');
document.write(result);
</script>
</body>
</html>
Open in new window