如何使用javascript替换字符串中变量的所有出现?

时间:2021-04-13 16:51:54

I'm trying to replace all the occurrences of a variable in a string using javascript.

我正在尝试使用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:

这只是替换第一次出现的id:

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

What am I doing wrong here?

我在这做错了什么?

Thanks

2 个解决方案

#1


11  

When you instantiate the RegExp object, you don't need to use slashes; the flags are passed as a second argument. For example:

实例化RegExp对象时,不需要使用斜杠;标志作为第二个参数传递。例如:

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

#2


0  

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

您需要在要替换的字符串之前和之后使用斜杠(id)。

Example

#1


11  

When you instantiate the RegExp object, you don't need to use slashes; the flags are passed as a second argument. For example:

实例化RegExp对象时,不需要使用斜杠;标志作为第二个参数传递。例如:

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

#2


0  

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

您需要在要替换的字符串之前和之后使用斜杠(id)。

Example