JavaScript RegExp在replace()中不起作用 [英] JavaScript RegExp in replace() not working
本文介绍了JavaScript RegExp在replace()中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码
var str = "Some text :$0";
var i = 0;
alert(str.replace(new RegExp("\:\$" + i, "g"), 'here'));
请参见此处.
为什么它不起作用?如果我这样做/\:\ $:0/g
而不是使用 RegExp
对象,那么它可以工作,但是我不能在模式中使用变量办法.怎么了?
Why is it not working? If I do it like this /\:\$:0/g
instead of using the RegExp
object then it works but I can't use a variable in the pattern that way. Whats wrong?
推荐答案
由于在字符串文字中, \
具有特殊含义.如果要在正则表达式中实际放置 \
,则需要在字符串文字中对其进行转义:
Because in string literals, \
has a special meaning. If you want to actually put a \
in the regular expression, you need to escape it in the string literal:
new RegExp("\\:\\$" + i, "g")
但是:
在正则表达式中没有特殊含义,无需转义:
But :
has no special meaning in regular expressions, no need to escape it:
new RegExp(":\\$" + i, "g")
var str = "Some text :$0";
var i = 0;
console.log(str.replace(new RegExp(":\\$" + i, "g"), 'here'));
这篇关于JavaScript RegExp在replace()中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文