JavaScript create regex programmatically -
i know can create javascript replace this:
str = str.replace(/mytarget/g, 'some value');
that replace occurrences of literal mytarget
. however, have big array of words/phrases want use in regex replace, , regexps language elements (they not wrapped in string when declaring), can't find way declare regexps programmatically unless hard-code them. if have:
var arr=['word', 'another', 'hello'];
i want produce:
str = str.replace(/word/g, 'some value');
str = str.replace(/another/g, 'some value');
str = str.replace(/hello/g, 'some value');
please post example can use regexps, i'll adding more expressions regexps such whitespace etc. need regexp way. finally, please don't offer using eval
, i'm sure there better way.
you need invoke regexp constructor function that. example:
['word', 'another', 'hello'].foreach(function( word ) { var myexp = new regexp(word, 'g'); str = str.replace(myexp, 'some value'); });
the first argument constructor string, literally takes wrap inbetween //
. second paramter string, can pass modifiers g
, i
, etc.
Comments
Post a Comment