javascript replace all with string code example

Example 1: js string replaceall

// Chrome 85+
str.replaceAll(val, replace_val);
// Older browsers
str.replace(/val/g, replace_val);

Example 2: js replace characters in a string

var str = "Original string!";
var str = str.replace("Original", "New");

Example 3: replace all occurrences of a string in javascript

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"

Example 4: replace all js

let a = 'a a a a aaaa aa a a';
a.replace(/aa/g, 'bb');
// => "a a a a bbbb bb a a"

Example 5: javascript replaceall

//as of August 2020, not supported on older browsers
str.replaceAll("abc","def")

Example 6: javascript replace all with variable

/**
*A better method for replacing strings is as follows:
**/
function replaceString(oldString, newString, fullString) {
  return fullS.split(oldS).join(newS)
}
replaceString('World', 'Web', 'Brave New World')//'Brave New Web'
replaceString('World', 'Web', 'World New World')//'Web New Web'