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.
This question is related to
javascript
variables
match
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)
xxx.match(yyy, 'g').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);
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];
}
}
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);
Source: Stackoverflow.com