4

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

2 Answers 2

12

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");
Sign up to request clarification or add additional context in comments.

1 Comment

This won't work if there are regex characters in id
0

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

Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.