Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 439
marcgg Avatar asked Dec 17 '22 06:12

marcgg


1 Answers

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");
like image 79
VoteyDisciple Avatar answered Mar 01 '23 22:03

VoteyDisciple