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.
You need to invoke the RegExp constructor function for that. Example:
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 likeg,i, etc.