Monday, 16 January 2017

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



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?


Answer




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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...