如何在 jQuery/Javascript 中将变量传递给正则表达式

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

How to pass a variable into regex in jQuery/Javascript

jqueryregexmatch

提问by Jonathan Lonowski

Is there a way to pass a variable into a regex in jQuery/Javascript?

有没有办法将变量传递给 jQuery/Javascript 中的正则表达式?

I wanna do something like:

我想做这样的事情:

var variable_regex = "bar";
var some_string = "foobar";

some_string.match(/variable_regex/);

In Ruby you would be able to do:

在 Ruby 中,您可以执行以下操作:

some_string.match(/#{variable_regex}/)

some_string.match(/#{variable_regex}/)

Found a useful post:

找到一个有用的帖子:

How can I concatenate regex literals in JavaScript?

如何在 JavaScript 中连接正则表达式文字?

采纳答案by Jonathan Lonowski

It's easy:

这很简单:

var variable_regex = "bar";
var some_string = "foobar";

some_string.match(variable_regex);

Just lose the //. If you want to use complex regexes, you can use string concatenation:

只是失去了//。如果要使用复杂的正则表达式,可以使用字符串连接:

var variable_regex = "b.";
var some_string = "foobar";

alert (some_string.match("f.*"+variable_regex));

回答by Jonathan Lonowski

Javascript doesn't support interpolation like Ruby -- you have to use the RegExpconstructor:

Javascript 不支持像 Ruby 那样的插值——你必须使用RegExp构造函数:

var aString = "foobar";
var pattern = "bar";

var matches = aString.match(new RegExp(pattern));