1var str = "JavaScript replace method test";
2var res = str.replace("test", "success");
3//res = Javscript replace method success
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");
1let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
2// `result` is "1 xyz 2 xyz 3"