There is an array
var words =new Array(
'apple',
'apa',
'found',
'stackoverflow',
'will'
);
and a variable
var search = 'papa.com';
Now I want to set an expression like this
var Flag=false;
var regexp;
for(var i in words)
{
regexp = new RegExp('(^(.*\.))?' + words[i] + '\.([a-z]{2,3})(\.(\w+))?','i');
if (regexp.test(search)) {Flag=true;}
}
alert (Flag);
The loop is supposed to get words array keys one by one, then set the regular expression and test the search variable against the built expression, if there where one or more match the Flag will come out with true.
But, id doesn’t work.
You need to escape your escape sequences when you build a regex from a string. This is because a
\in string literal notation also begins an escape sequence, and so the\is removed.To include a literal
\character in a string built from literal syntax, you need\\.Your regex was ending up with
.instead of\., which would of course have very different meaning.