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
5// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
6
7
8
9
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");
1// Update: In the latest versions of most popular browsers,
2// you can use replaceAll as shown here:
3let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
4// `result` is "1 xyz 2 xyz 3"
5
6/*
7For Node and compatibility with older/non-current browsers:
8Note: Don't use the following solution in performance critical code.
9As an alternative to regular expressions for a simple literal string,
10you could use:
11*/
12str = "Test abc test test abc test...".split("abc").join("");
13
14// ass a general pattern
15// str.split(search).join(replacement)
16