Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

javascript - 如何在正则表达式中使用变量?(How do you use a variable in a regular expression?)

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.

(我想在JavaScript中创建String.replaceAll()方法,并且我认为使用正则表达式是最简洁的方法。)

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" .

(我已经可以这样做了,它将用"A"替换"B"所有实例。)

"ABABAB".replace(/B/g, "A");

But I want to do something like this:

(但是我想做这样的事情:)

String.prototype.replaceAll = function(replaceThis, withThis) {
    this.replace(/replaceThis/g, withThis);
};

But obviously this will only replace the text "replaceThis" ...so how do I pass this variable in to my regex string?

(但是显然,这只会替换文本"replaceThis" ...所以如何将这个变量传递给我的正则表达式字符串?)

  ask by JC Grubbs translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of using the /regex/g syntax, you can construct a new RegExp object:

(您可以构造一个新的RegExp对象, /regex/g使用/regex/g语法:)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...