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.
This question is related to
javascript
regex
dynamic
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);
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...
Source: Stackoverflow.com