How to put variable in regular expression match?

JavascriptRegex

Javascript Problem Overview


I have the following snippet. I want to find the appearance of a, but it does not work. How can I put the variable right?

var string1 = 'asdgghjajakhakhdsadsafdgawerwweadf';
var string2 = 'a';
string1.match('/' + string2 + '/g').length;

Javascript Solutions


Solution 1 - Javascript

You need to use the RegExp constructor instead of a regex literal.

var string = 'asdgghjjkhkh';
var string2 = 'a';
var regex = new RegExp( string2, 'g' );
string.match(regex);

If you didn't need the global modifier, then you could just pass string2, and .match() will create the regex for you.

string.match( string2 );

Solution 2 - Javascript

If you are merely looking to check whether a string contains another string, then your best bet is simply to use match() without a regex.

You may object: But I need a regex to check for classes, like \s, to define complicated patterns, etc..

In that case: You will need change the syntax even more, double-escaping your classes and dropping starting/ending / regex indicator symbols.

Imagine this regex...

someString.match(/\bcool|tubular\b);

The exact equivalent of this, when using a new new RegExp(), is...

someStringRegex = new RegExp('\\bcool|tubular\\b');

Two things happened in this transition:

  • Drop the opening and closing / (otherwise, your regex will fail).
  • Double escape your character classes, like \b becomes \\b for word borders, and \w becomes \\w for whitespace, etc. (otherwise, your regex will fail).

Solution 3 - Javascript

Here is another example- //confirm whether a string contains target at its end (both are variables in the function below, e.g. confirm whether str "Abstraction" contains target "action" at the end).

function confirmEnding(string, target) {
    let regex = new RegExp(target);
    return regex.test(string);
};

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
QuestionsomebodyelseView Question on Stackoverflow
Solution 1 - Javascriptuser113716View Answer on Stackoverflow
Solution 2 - JavascriptHoldOffHungerView Answer on Stackoverflow
Solution 3 - JavascriptSnowcatView Answer on Stackoverflow