在javascript中将变量传递给regexp [英] passing variable to a regexp in javascript
问题描述
可能重复:
用于Javascript正则表达式的转义字符串
我有这样的消息:
{1}中允许的最多{0}个字符
我有一个函数来使用传递的参数创建一个消息
And I have a function to create a message using the arguments passed as
for(var i = 0; i < agrs.length; i++){
reg = new RegExp('\{'+i+'\}', 'gi');
key = key.replace(reg,agrs[i])
}
问题是它无法使用参数 i
来创建reg exp。
The problem is that it's not able to take the param i
to create the reg exp.
这是什么方式实现这个目标?
What's the way to achieve this?
推荐答案
你的正则表达式是 / {0} / gi
因为你是从字符串创建它。它不是一个有效的表达方式。
你需要在regexp中转义{因为它在regexp语法中有特殊含义,所以它应该是:
Your regexp is /{0}/gi
since you create it from a string. And it is not a valid expression.
You need to escape { in the regexp because it has a special meaning in the regexp syntax, so it should be:
new RegExp('\\{'+i+'\\}', 'gi');
这是 / \\ {0\\} / GI
。您需要在字符串中转义转义 \\
。
which is /\\{0\\}/gi
. You need to escape the escaping \\
in the string.
这篇关于在javascript中将变量传递给regexp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!