replace all occurrences of a string in javascript
snippet in javascript

replace all occurrences of a string in javascript

user7515

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"

javascript replace string

user1485

var str = "JavaScript replace method test";
var res = str.replace("test", "success");  
//res = Javscript replace method success

javascript replace all occurrences of string

user1129

function replaceAll(str, find, replace) {
    var escapedFind=find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    return str.replace(new RegExp(escapedFind, 'g'), replace);
}
//usage example
var sentence="How many shots did Bill take last night? That Bill is so crazy!";
var blameSusan=replaceAll(sentence,"Bill","Susan"); 

str replace javascript all

user1070

str.replace(/abc/g, '');

javascript replace all occurrences

user7699

str = str.replace(/abc/g, '');

replace all javascript

user3812

str.split(search).join(replacement);