admin管理员组

文章数量:1335401

I am desperate - I don't see what I'm doing wrong. I try to replace all occurrences of '8969' but I always get the original string (no matter whether tmp is a string or an int). Maybe it's already too late, maybe I'm blind, ...

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

Can someone help me out?

I am desperate - I don't see what I'm doing wrong. I try to replace all occurrences of '8969' but I always get the original string (no matter whether tmp is a string or an int). Maybe it's already too late, maybe I'm blind, ...

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

Can someone help me out?

Share Improve this question edited May 1, 2012 at 23:28 gdoron 150k59 gold badges302 silver badges371 bronze badges asked May 1, 2012 at 21:38 user1000742user1000742 1832 silver badges10 bronze badges 1
  • 1 Why do you use such expression /tmp/g? – Lion Commented May 1, 2012 at 21:41
Add a ment  | 

5 Answers 5

Reset to default 8

The / characters are the container for a regular expression in this case. 'tmp' is therefore not used as a variable, but as a literal string.

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

or

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

Live DEMO

Dynamic way of handling a regex:

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

/tmp/g. This is a regex looking for the phrase "tmp". You need to use new RegExp to make a dynamic regex.

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

Javascript doesn't support that usage of tmp, it will try to use 'tmp' literally, as a regex pattern.

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

本文标签: javascriptHow to use a variable value as a regex patternStack Overflow