JavaScript - Use variable in string match

mesnicka picture mesnicka · Jul 3, 2010 · Viewed 118k times · Source

I found several similar questions, but it did not help me. So I have this problem:

var xxx = "victoria";
var yyy = "i";
alert(xxx.match(yyy/g).length);

I don't know how to pass variable in match command. Please help. Thank you.

Answer

Chris Hutchinson picture Chris Hutchinson · Jul 3, 2010

Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:

var re = new RegExp(yyy, 'g');
xxx.match(re);

Any flags you need (such as /g) can go into the second parameter.