Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regexp dynamic generation from variables? [duplicate]

How to construct two regex patterns into one?

For example I have one long pattern and one smaller, I need to put smaller one in front of long one.

var pattern1 = ':\(|:=\(|:-\(';
var pattern2 = ':\(|:=\(|:-\(|:\(|:=\(|:-\('
str.match('/'+pattern1+'|'+pattern2+'/gi');

This doesn't work. When I'm concatenating strings, all slashes are gone.

like image 533
Somebody Avatar asked Feb 23 '11 11:02

Somebody


2 Answers

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 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
like image 113
Felix Kling Avatar answered Oct 08 '22 03:10

Felix Kling


Use the below:

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

str.match(regEx);
like image 29
adarshr Avatar answered Oct 08 '22 04:10

adarshr