160

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Somebody
  • 9,316
  • 26
  • 94
  • 142

4 Answers4

280

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 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
35

Use the below:

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

str.match(regEx);
adarshr
  • 61,315
  • 23
  • 138
  • 167
21

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);
alex
  • 479,566
  • 201
  • 878
  • 984
4

The RegExp constructor creates a regular expression object for matching text with a pattern.

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

Above code works perfectly for me...

Vinoth Narayan
  • 275
  • 2
  • 15