JavaScript-在字符串匹配中使用变量

我发现了几个类似的问题,但没有帮助到我,所以我有这个问题:

var xxx = "victoria";
var yyy = "i";
alert(xxx.match(yyy/g).length);

我不知道如何在 match 命令中传递变量。请帮助。谢谢。

148686 次浏览
xxx.match(yyy, 'g').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.

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

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)

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