mesnicka
mesnicka

Reputation: 2548

JavaScript - Use variable in string match

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.

Upvotes: 117

Views: 165466

Answers (7)

adB
adB

Reputation: 41

Below is an example of a simple and effective way to mock 'like' operator in JS. enjoy!

const likePattern = '%%i%%%%%a';
const regexp = new RegExp(likePattern.replaceAll('%','.*'),"i");
console.log("victoria".match(regexp));

Upvotes: 0

Driton Haxhiu
Driton Haxhiu

Reputation: 117

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)

Upvotes: 9

Sarvar Nishonboyev
Sarvar Nishonboyev

Reputation: 13090

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

Upvotes: 10

geekbuntu
geekbuntu

Reputation: 871

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

Upvotes: 0

Marcis
Marcis

Reputation: 4617

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

Upvotes: 18

Chris Hutchinson
Chris Hutchinson

Reputation: 9212

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.

Upvotes: 244

SilentGhost
SilentGhost

Reputation: 319601

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

Upvotes: -5

Related Questions