How to replace all occurrences of a variable in a string using javascript?

I am trying to replace all occurrences of a variable in a string using javascript.

This does not work.:

var id = "__1"; var re = new RegExp('/' + id + '/g'); var newHtml = oldHtml.replace( re, "__2"); 

This replaces only the first occurrence of id:

 var id = "__1"; var newHtml = oldHtml.replace( id,"__2"); 

What am I doing wrong here?

thanks

+4
source share
2 answers

When you instantiate a RegExp object, you do not need to use slashes; flags are passed as the second argument. For instance:

 var id = "__1"; var re = new RegExp(id, 'g'); var newHtml = oldHtml.replace( re, "__2"); 
+11
source

You need slashes before and after the line to replace (id).

Example

0
source

All Articles