简体   繁体   English

使用字符串的JavaScript正则表达式?

[英]JavaScript regex using strings?

How can I use strings as the 'find' in a JS regex? 如何在JS正则表达式中使用字符串作为“查找”?

ie: 即:

var find = ["a", "b", "c"];
var string = "abcdefghijkl";

Now, I want to replace all the elements of the array find, with a blank string ( " " ), using regular expressions. 现在,我想使用正则表达式用空白字符串( " " )替换数组find的所有元素。 How can I do this? 我怎样才能做到这一点?

I mean, using .replace(/find[i]/g, "") in a loop wouldn't work. 我的意思是,在循环中使用.replace(/find[i]/g, "")无效。

So, how can I do it? 那么,我该怎么办呢?

Thanks! 谢谢!

You can dynamically create regex with the built-in RegExp object. 您可以使用内置的RegExp对象动态创建正则表达式。

var find = ["a", "b", "c"];
var re = new RegExp( find.join("|"), "g" ); // <- /a|b|c/g
var string = "abcdefghijkl";

string = string.replace(re, "");

alert(string); // <- defghijkl
​

为什么不呢?

.replace(find[i], "*")

If you need to run the expressions one at a time (for exampe if they are too complex to just concatentate into a singe expression), you create Regexp objects in a loop like this: 如果您需要一次运行一个表达式(例如,如果它们太复杂以至于不能与一个单一的表达式相融合),则可以在这样的循环中创建Regexp对象:

var find = ["a", "b", "c"];
var string = "abcdefghijkl";

for (var i = 0; i < find.length; i++) {
  var re = new Regexp(find[i], "g");
  string = string.replace(re, "");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM