1const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
2
3console.log(p.replaceAll('dog', 'monkey'));
4// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
1const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
2
3console.log(p.replaceAll('dog', 'monkey'));
4// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
5
6// global flag required when calling replaceAll with regex
7const regex = /Dog/ig;
8console.log(p.replaceAll(regex, 'ferret'));
9// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
10
1function replaceAll(str, find, replace) {
2 var escapedFind=find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
3 return str.replace(new RegExp(escapedFind, 'g'), replace);
4}
5//usage example
6var sentence="How many shots did Bill take last night? That Bill is so crazy!";
7var blameSusan=replaceAll(sentence,"Bill","Susan");
1function name(str,replaceWhat,replaceTo){
2 replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
3 var re = new RegExp(replaceWhat, 'g');
4 return str.replace(re,replaceTo);
5}
1function name(str,replaceWhat,replaceTo){
2 var re = new RegExp(replaceWhat, 'g');
3 return str.replace(re,replaceTo);
4}
1/**
2*A better method for replacing strings is as follows:
3**/
4function replaceString(oldString, newString, fullString) {
5 return fullS.split(oldS).join(newS)
6}
7replaceString('World', 'Web', 'Brave New World')//'Brave New Web'
8replaceString('World', 'Web', 'World New World')//'Web New Web'