javascript - JS replacing all occurrences of string using variable -
this question has answer here:
- how use variable in regular expression? 16 answers
i know str.replace(/x/g, "y")
replaces x's in string want this
function name(str,replacewhat,replaceto){ str.replace(/replacewhat/g,replaceto); }
how can use variable in first argument?
the regexp
constructor takes string , creates regular expression out of it.
function name(str,replacewhat,replaceto){ var re = new regexp(replacewhat, 'g'); str.replace(re,replaceto); }
if replacewhat
might contain characters special in regular expressions, can do:
function name(str,replacewhat,replaceto){ replacewhat = replacewhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); var re = new regexp(replacewhat, 'g'); str.replace(re,replaceto); }
Comments
Post a Comment