December 2023
Intermediate to advanced
242 pages
5h 28m
English
The replaceAll() method outputs the same result as replace() when the global flag is set. Compare:
| | const str = "$5, $10, $20"; |
| | const re = /\$/g; |
| | |
| | console.log(str.replace(re, "€")); // → €5, €10, €20 |
| | console.log(str.replaceAll(re, "€")); // → €5, €10, €20 |
As a result, calling replaceAll() doesn’t seem to yield much benefit over calling replace(). The main difference between the two methods is how replaceAll() handles replacement when the pattern is a string, as opposed to a regex:
| | const str = "$5, $10, $20"; |
| | const searchStr = "$"; |
| | |
| | console.log(str.replace(searchStr, "€")); // → €5, $10, $20 |
| | console.log(str.replaceAll(searchStr, ... |
Read now
Unlock full access