JS Built-ins
← String112 / 195
StringString.prototype.replaceAllbeginner

String.prototype.replaceAll() β€” vs replace (only first)

πŸ“– Usage Example
'foo bar foo'.replaceAll('foo', 'baz')  // β†’ 'baz bar baz'
'banana'.replaceAll('a', 'o')           // β†’ 'bonono'

Use replaceAll() to replace every occurrence of a search string or regex (with /g flag) with the replacement.

replaceAll vs replace

.replace(str) only replaces the first match. .replaceAll(str) replaces all matches.

Challenge: Implement countReplacements(str, from, to) and show it replaces more than replace alone would.

'aaa'.replace('a', 'b')    // β†’ 'baa'
'aaa'.replaceAll('a', 'b') // β†’ 'bbb'
πŸ’‘ Hints (2)
  • β€’ `str.replace("a", "b")` only replaces the first `"a"` found.
  • β€’ `str.replaceAll("a", "b")` replaces every `"a"` in the string.