Q:

how to replace all the string in javascript when the string is javascript variable

const p = 'dog dog cat rat';

const regex = /dog/gi;

console.log(p.replace(regex, 'cow'));
//if pattern is regular expression all matches will be replaced
//output: "cow cow cat rat"
25
function name(str,replaceWhat,replaceTo){
    replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    var re = new RegExp(replaceWhat, 'g');
    return str.replace(re,replaceTo);
}
1
str = str.replace(new RegExp('abc', 'g'), 'xyz');
2
function name(str,replaceWhat,replaceTo){
    var re = new RegExp(replaceWhat, 'g');
    return str.replace(re,replaceTo);
}
0

New to Communities?

Join the community