最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript RegExp string pattern - Stack Overflow

programmeradmin4浏览0评论

I need to check 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.

I need to check 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.

Share Improve this question asked Jan 8, 2010 at 18:49 RohanRohan 1,6573 gold badges16 silver badges24 bronze badges 1
  • what are you trying to match? You are correct though, if you neet to dynamically create the regex, you will need to use new RegExp("string");. – Kevin Peno Commented Jan 8, 2010 at 18:54
Add a ment  | 

3 Answers 3

Reset to default 7

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)

  1. 暂无评论