Skip to content Skip to sidebar Skip to footer

How To Replace All Occurences Of A Variable In A String Using Javascript?

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 = old

Solution 1:

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 = newRegExp(id, 'g');
var newHtml = oldHtml.replace( re, "__2");

Solution 2:

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

Example

Post a Comment for "How To Replace All Occurences Of A Variable In A String Using Javascript?"