JS Built-ins
← String106 / 195
StringString.prototype.replacebeginner

String.prototype.replace() β€” replace first occurrence

πŸ“– Usage Example
'foo bar foo'.replace('foo', 'baz')    // β†’ 'baz bar foo'
'hello'.replace(/[aeiou]/g, '*')       // β†’ 'h*ll*'

Use replace() to replace the first occurrence of a pattern; use a /g regex to replace all occurrences.

String.prototype.replace()

str.replace(searchValue, replaceValue) returns a new string with the first occurrence of searchValue replaced by replaceValue.

Challenge: Implement replaceFirst(str, from, to) that replaces the first occurrence of from with to.

replaceFirst('foo bar foo', 'foo', 'baz') // β†’ 'baz bar foo'
πŸ’‘ Hints (2)
  • β€’ `str.replace(string, replacement)` only replaces the first match.
  • β€’ Use `replaceAll` or a `/g` regex to replace all occurrences.