Javascript Regexp dynamic generation from variables?

JavascriptRegexDynamic

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';

Solution 2 - Javascript

Use the below:

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

str.match(regEx);

Solution 3 - Javascript

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);

Solution 4 - Javascript

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...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSomebodyView Question on Stackoverflow
Solution 1 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 2 - JavascriptadarshrView Answer on Stackoverflow
Solution 3 - JavascriptalexView Answer on Stackoverflow
Solution 4 - JavascriptVinoth NarayanView Answer on Stackoverflow