Link to home
Start Free TrialLog in
Avatar of ahmeix0l
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
<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>

Open in new window

Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Here


<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);
</script>
 
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ahmeix0l
ahmeix0l

ASKER

I think  str.replace(old,news); also does the job,
Thanks dude.
Not completely since you miss the gi.
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