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?"
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 string = 'soandso, my name is soandso';
2
3let replaced = string.replace(/soandso/gi, 'Dylan');
4
5console.log(replaced); //Dylan, my name is Dylan
1// siingle replace
2"str".replace('s', 'a') // atr
3"str".replace(/s|r/, 'a') //ata
4
5// replace all occurrences
6"strstr".replace(/s/, 'a') //atratr
7
8// replace with a function
9function replacer(match, p1, p2, p3, offset, string) {
10 // p1 is nondigits, p2 digits, and p3 non-alphanumerics
11 return [p1, p2, p3].join(' - ');
12}
13let newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
14console.log(newString); // abc - 12345 - #$*%
15