javascript - JS replacing all occurrences of string using variable -


this question has answer here:

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); } 

see is there regexp.escape function in javascript?


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -