The library notice board: replace or replaceAll, how many pieces does each swap? The swapped pieces are marked and checked against the JS engine. An…
Swapping every occurrence is everyday work (cleaning text, formatting, templates). Using .replace() wrong is a silent bug: some stay unchanged. Knowing replaceAll from a /g regex means correct code, safe from escaping traps.
.replace(string) swaps only the first, replaceAll swaps them all
.replace('x','y') to swap them all Only the first. Use .replaceAll, or a /x/g regex if you really need a pattern./g regex from dynamic input Regex special characters in a user's string make the pattern wrong or an error. replaceAll with a string (literal) is safe with no escaping.replaceAll a regex without g replaceAll(/x/, …) throws a TypeError: the g flag is required. On purpose, so "replace all" is written down..replace to .replaceAll with a string needle Every occurrence is swapped, no regex, no escaping.. with a regex needle and g In a regex, . means any character: the pattern matches far more than the dots there are.( or * The regex is refused: a SyntaxError. A string needle stays right.replaceAll with a regex without g It throws a TypeError: the "all" has to be written in the regex too.