如何在正则表达式中使用变量? [英] How do you use a variable in a regular expression?
问题描述
我想在JavaScript中创建一个String.replaceAll()方法,我认为使用RegEx将是最简洁的方法。但是,我无法弄清楚如何将变量传递给RegEx。我已经可以做到这一点,它将用A替换所有B的实例。
I would like to create a String.replaceAll() method in JavaScript and I'm thinking that using a RegEx would be most terse way to do it. However, I can't figure out how to pass a variable in to a RegEx. I can do this already which will replace all the instances of "B" with "A".
"ABABAB".replace(/B/g, "A");
但我想做这样的事情:
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
但显然这只会替换文本replaceThis...所以如何传递这个变量在我的RegEx字符串中?
But obviously this will only replace the text "replaceThis"...so how do I pass this variable in to my RegEx string?
推荐答案
而不是使用 / regex / g
语法,您可以构建一个新的 RegExp 对象:
Instead of using the /regex/g
syntax, you can construct a new RegExp object:
var replace = "regex";
var re = new RegExp(replace,"g");
您可以通过这种方式动态创建正则表达式对象。然后你会这样做:
You can dynamically create regex objects this way. Then you will do:
"mystring".replace(re, "newstring");
这篇关于如何在正则表达式中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!