[英]Javascript RegExp string pattern
I need to check JS matches for a dynamically generated string. 我需要检查JS匹配动态生成的字符串。
ie. 即。
for(i=0; i< arr.length; i++)
{
pattern_1="/part of "+arr[i]+" string!/i";
if( string.search(pattern_1) != -1)
arr_num[i]++;
}
However, this code doesn't work - I presume due to the quotes. 但是,这段代码不起作用 - 我假设由于引号。 How do I do this?
我该怎么做呢?
Many thanks. 非常感谢。
The /pattern/
literal only works as, well, a literal. /pattern/
literal只能用作文字。 Not within a string. 不在字符串中。
If you want to use a string pattern to create a regular expression, you need to create a new RegExp object: 如果要使用字符串模式创建正则表达式,则需要创建新的RegExp对象:
var re = new RegExp(pattern_1)
And in that case, you would omit the enclosing frontslashes ( /
). 在这种情况下,您将省略封闭的前缀(
/
)。 These two lines are equivalent: 这两行是等价的:
var re = /abc/g;
var re = new RegExp("abc", "g");
The problem is that you are passing a string to the search
function so it treats it as a string. 问题是您将字符串传递给
search
功能,因此它将其视为字符串。 Try using a RegExp object like so: 尝试使用RegExp对象,如下所示:
myregexp = new RegExp("part of " + arr[i] + " string!", "i")
if (string.search(myregexp) != -1) {
arr_num[i]++;
}
Try this: 尝试这个:
// note you dont need those "/" and that "i" modifier is sent as second argument
pattern_1= new RegExp("part of "+arr[i]+" string!", "i");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.