如何将变量值用作正则表达式模式

时间:2012-05-01 21:38:32

标签: javascript regex replace

我很绝望 - 我看不出我做错了什么。我尝试替换所有出现的'8969',但我总是得到原始字符串(无论tmp是字符串还是int)。也许已经太晚了,也许我是瞎了,......

var tmp = "8969";
alert("8969_8969".replace(/tmp/g, "99"));

有人能帮助我吗?

5 个答案:

答案 0 :(得分:8)

在这种情况下,/个字符是正则表达式的容器。因此,'tmp'不用作变量,而是用作文字字符串。

var tmp = /8969/g;
alert("8969_8969".replace(tmp, "99"));

答案 1 :(得分:5)

alert("8969_8969".replace(/8969/g, "99"));

var tmp = "8969"
alert("8969_8969".replace(new RegExp(tmp,"g"), "99")); 

Live DEMO

答案 2 :(得分:3)

处理正则表达式的动态方式:

var nRegExp = new RegExp("8969", 'g');
alert("8969_8969".replace(nRegExp, "99"));

答案 3 :(得分:2)

/tmp/g。这是一个正在寻找短语"tmp"的正则表达式。您需要使用new RegExp制作动态正则表达式。

alert("8969_8969".replace(new RegExp(tmp,'g'), "99"));

答案 4 :(得分:-1)

Javascript不支持 使用tmp,它会尝试使用'tmp'作为正则表达式模式。

"8969_8969".replace(new RegExp(tmp,'g'), "99")
相关问题