views:

199

answers:

2

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

+7  A: 

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");
VoteyDisciple
it worked like a charm, thank you!
marcgg
A: 

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

Example

mcandre