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
5 Answers
Reset to default 8The /
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
版权声明:本文标题:javascript - How to use a variable value as a regex pattern - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742386971a2465227.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论