string substitution javascript code example
Example 1: javascript replace
var res = str.replace("find", "replace");
Example 2: javascript replace all occurrences of string
function replaceAll(str, find, replace) {
var escapedFind=find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return str.replace(new RegExp(escapedFind, 'g'), replace);
}
var sentence="How many shots did Bill take last night? That Bill is so crazy!";
var blameSusan=replaceAll(sentence,"Bill","Susan");
Example 3: javascript string interpolation
var animal = "cow";
var str=`The ${animal} jumped over the moon`;
Example 4: how to use the replace method in javascript
let string = 'soandso, my name is soandso';
let replaced = string.replace(/soandso/gi, 'Dylan');
console.log(replaced);
Example 5: javascript template literals
let a = 5;
let b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);