JS Built-ins
← String109 / 195
StringString.prototype.replaceintermediate

String.prototype.replace() β€” capture groups in replacement

πŸ“– 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() β€” Capture Groups

Use $1, $2, etc. in the replacement string to reference captured groups.

Challenge: Implement swapWords(str) that swaps two space-separated words.

swapWords('hello world') // β†’ 'world hello'
πŸ’‘ Hints (2)
  • β€’ `/(\w+) (\w+)/` captures two words separated by a space.
  • β€’ `$1` and `$2` refer to the first and second captured groups.