Javascript Regexp dynamic generation from variables? [duplicate] Javascript Regexp dynamic generation from variables? [duplicate] javascript javascript

Javascript Regexp dynamic generation from variables? [duplicate]


You have to use RegExp:

str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));

When I'm concatenating strings, all slashes are gone.

If you have a backslash in your pattern to escape a special regex character, (like \(), you have to use two backslashes in the string (because \ is the escape character in a string): new RegExp('\\(') would be the same as /\(/.

So your patterns have to become:

var pattern1 = ':\\(|:=\\(|:-\\(';var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';


Use the below:

var regEx = new RegExp(pattern1+'|'+pattern2, 'gi');str.match(regEx);


You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.

var regex = new RegExp(pattern1+'|'+pattern2, 'gi');str.match(regex);