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"

function name(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}

function name(str,replaceWhat,replaceTo){
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}

www.codegrepper.com
www.stackoverflow.com

how to put variable in string javascript


var myInt = 1
console.log(`my variable is ${myInt}`);
// my variable is 1

var myInt = 1
console.log("my variable is ${myInt}");
// my variable is 1

var myBool = true
console.log("my variable is ${(myBool) ? 'x' : 'y'}");
// my variable is x

var myNumberA, myNumberB = 3;
console.log("my variable is ${myNumberA * myNumberB}");
// my variable is 9

www.codegrepper.com
www.stackoverflow.com