开发者

Javascript RegExp string pattern

开发者 https://www.devze.com 2022-12-15 17:24 出处:网络
I need to chec开发者_如何学Ck JS matches for a dynamically generated string. ie. for(i=0; i< arr.length; i++)

I need to chec开发者_如何学Ck JS matches for a dynamically generated string.

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. 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:

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");


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");


The problem is that you are passing a string to the search function so it treats it as a string. Try using a RegExp object like so:

myregexp = new RegExp("part of " + arr[i] + " string!", "i")
if (string.search(myregexp) != -1) {
   arr_num[i]++;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消