JavaScript - Use variable in string match
Example. To find number of vowels within the string
var word='Web Development Tutorial';
var vowels='[aeiou]';
var re = new RegExp(vowels, 'gi');
var arr = word.match(re);
document.write(arr.length);
You have to use RegExp object if your pattern is string
var xxx = "victoria";
var yyy = "i";
var rgxp = new RegExp(yyy, "g");
alert(xxx.match(rgxp).length);
If pattern is not dynamic string:
var xxx = "victoria";
var yyy = /i/g;
alert(xxx.match(yyy).length);
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.
For example:
let myString = "Hello World"
let myMatch = myString.match(/H.*/)
console.log(myMatch)
Or
let myString = "Hello World"
let myVariable = "H"
let myReg = new RegExp(myVariable + ".*")
let myMatch = myString.match(myReg)
console.log(myMatch)