I know that I can create a javascript replace like this:
str = str.replace(/mytarget/g, 'some value');
that will replace all the occurrences of the literal mytarget
.
However, I have a big array of words/phrases that I want to use in regex replace, and as regexps are just language elements (they are not wrapped in a string when declaring), I can't find a way to declare regexps programmatically unless I hard-code them. So if I have:
var arr=['word', 'another', 'hello'];
I want to produce:
str = str.replace(/word/g, 'some value');
str = str.replace(/another/g, 'some value');
str = str.replace(/hello/g, 'some value');
Please post an example that I can use regexps, as I'll be adding more expressions into the regexps such as whitespace etc. so I NEED it开发者_StackOverflow the regexp way. Finally, please don't offer using eval
, I'm sure there is a better way.
You need to invoke the RegExp constructor function for that. Example:
['word', 'another', 'hello'].forEach(function( word ) {
var myExp = new RegExp(word, 'g');
str = str.replace(myExp, 'some value');
});
The first argument for the constructor is a string, which literally takes anything you would wrap inbetween //
. The second paramter is also string, where you can pass modifiers like g
, i
, etc.
You can build a RegEx dynamically like this -
var word = 'hello';
var re = new RegExp("\\b" + word + "\\b","g");
Remember that you'll need to escape any \
characters using \\
for( i in arr )
{
str = str.replace(new RegExp("\\"+arr[i],"g"), "some value")
}
If you are generating the reg-exp on the fly, you can use the RegExp object
var a = new RegExp("word")
精彩评论