如何在 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
How to pass a variable into regex in jQuery/Javascript
提问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:
找到一个有用的帖子:
采纳答案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 RegExp
constructor:
Javascript 不支持像 Ruby 那样的插值——你必须使用RegExp
构造函数:
var aString = "foobar";
var pattern = "bar";
var matches = aString.match(new RegExp(pattern));