I'm trying to replace all the occurrences of a variable in a string using javascript.
This is not working.:
var id = "__1";
var re = new RegExp('/' + id + '/g');
var newHtml = oldHtml.replace( re, "__2");
This is only replacing the first occurrence of id:
var id = "__1";
var newHtml = oldHtml.replace( id,"__2");
What am I doing wrong here?
Thanks
When you instantiate the RegExp object, you don't need to use slashes; the flags are passed as a second argument. For example:
var id = "__1";
var re = new RegExp(id, 'g');
var newHtml = oldHtml.replace( re, "__2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With