replace all js string code example
Example 1: js string replaceall
str.replaceAll(val, replace_val);
str.replace(/val/g, replace_val);
Example 2: replace all occurrences of a string in javascript
const p = 'dog dog cat rat';
const regex = /dog/gi;
console.log(p.replace(regex, 'cow'));
Example 3: how to replace all the string in javascript when the string is javascript variable
function name(str,replaceWhat,replaceTo){
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
Example 4: javascript replace all with variable
function replaceString(oldString, newString, fullString) {
return fullS.split(oldS).join(newS)
}
replaceString('World', 'Web', 'Brave New World')
replaceString('World', 'Web', 'World New World')