Javascript RegExp String String

I need to check JS matches for a dynamically generated string.

t

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 does not work - I suppose because of quotes. How to do it?

Many thanks.

+3
source share
3 answers

A literal /pattern/only works as a literal. Not inside the line.

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 this case, you lower the closing front legs ( /). These two lines are equivalent:

var re = /abc/g;
var re = new RegExp("abc", "g");
+7
source

, search, . RegExp :

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

Try the following:

// note you dont need those "/" and that "i" modifier is sent as second argument
pattern_1= new RegExp("part of "+arr[i]+" string!", "i");
+1
source

Source: https://habr.com/ru/post/1727800/


All Articles