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.
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.
match method is not a RegExp object, internally the RegExp constructor will be invoked using that value, so you can use a string pattern, e.g.: "a123".match("\\d+")[0] === "123";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);
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)
for me anyways, it helps to see it used. just made this using the "re" example:
var analyte_data = 'sample-'+sample_id;
var storage_keys = $.jStorage.index();
var re = new RegExp( analyte_data,'g');
for(i=0;i<storage_keys.length;i++) {
if(storage_keys[i].match(re)) {
console.log(storage_keys[i]);
var partnum = storage_keys[i].split('-')[2];
}
}
xxx.match(yyy, 'g').length
String.prototype.match method expects only one argument. Using the RegExp constructor, as @Chris suggests is the preferred way.
SyntaxError: Invalid regular expression: /c++/: Nothing to repeat