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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3172985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:32:21  来源:igfitidea点击:

JavaScript - Use variable in string match

javascriptvariablesmatch

提问by mesnicka

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.

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

回答by Chris Hutchinson

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:

尽管 match 函数不接受字符串文字作为正则表达式模式,但您可以使用 RegExp 对象的构造函数并将其传递给 String.match 函数:

var re = new RegExp(yyy, 'g');
xxx.match(re);

Any flags you need (such as /g) can go into the second parameter.

您需要的任何标志(例如 /g)都可以进入第二个参数。

回答by Anpher

You have to use RegExp objectif your pattern is string

如果您的模式是字符串,则必须使用RegExp 对象

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

回答by Driton Haxhiu

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)

回答by Sarvar Nishonboev

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

回答by geekbuntu

for me anyways, it helps to see it used. just made this using the "re" example:

无论如何,对我来说,看到它被使用是有帮助的。刚刚使用“re”示例进行了此操作:

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

回答by SilentGhost

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