Javascript 如何将变量放入正则表达式匹配中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7053506/
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-24 00:37:18  来源:igfitidea点击:

How to put variable in regular expression match?

javascriptregex

提问by somebodyelse

I have

我有

var string1 = 'asdgghjajakhakhdsadsafdgawerwweadf';
var string2 = 'a';
string1.match("\/"+string2+"\/g").length;

So with this I want to find the appearance of a, but it does not work. How can I put the variable right?

所以这个我想找到的出现一个,但它不工作。我怎样才能把变量放在正确的位置?

回答by user113716

You need to use the RegExpconstructor instead of a regex literal.

您需要使用RegExp构造函数而不是正则表达式文字。

var string = 'asdgghjjkhkh';
var string2 = 'a';
var regex = new RegExp( string2, 'g' );
string.match(regex);

If you didn't need the global modifier, then you could just pass string2, and .match()will create the regex for you.

如果您不需要全局修饰符,那么您可以只传递string2,并.match()为您创建正则表达式。

string.match( string2 );

回答by Snowcat

Here is another example- //confirm whether a string contains target at its end (both are variables in the function below, e.g. confirm whether str "Abstraction" contains target "action" at the end).

这是另一个例子- //确认一个字符串在其末尾是否包含目标(两者都是下面函数中的变量,例如确认 str "Abstraction" 在末尾是否包含目标 "action")。

function confirmEnding(string, target) {
    let regex = new RegExp(target);
    return regex.test(string);
};