JavaScript - Use variable in string match

JavascriptVariablesMatch

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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)

Solution 4 - Javascript

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

Solution 5 - Javascript

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];
    }
}

Solution 6 - Javascript

xxx.match(yyy, 'g').length

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmesnickaView Question on Stackoverflow
Solution 1 - JavascriptChris HutchinsonView Answer on Stackoverflow
Solution 2 - JavascriptAnpherView Answer on Stackoverflow
Solution 3 - JavascriptDriton HaxhiuView Answer on Stackoverflow
Solution 4 - JavascriptnsvView Answer on Stackoverflow
Solution 5 - JavascriptgeekbuntuView Answer on Stackoverflow
Solution 6 - JavascriptSilentGhostView Answer on Stackoverflow