如何在正则表达式中使用变量? [英] How do you use a variable in a regular expression?

查看:184
本文介绍了如何在正则表达式中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆