Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript create regex programmatically

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 the regexp way. Finally, please don't offer using eval, I'm sure there is a better way.

like image 508
Can Poyrazoğlu Avatar asked Oct 10 '11 18:10

Can Poyrazoğlu


1 Answers

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.

like image 186
jAndy Avatar answered Sep 21 '22 03:09

jAndy