How to put variable in regular expression match?

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;

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *