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

String.prototype.replace() β€” replace with function

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

The second argument can be a function. It receives the matched substring and returns the replacement.

Challenge: Implement doubleNumbers(str) that doubles every digit found in the string.

doubleNumbers('a1b2') // β†’ 'a2b4'
πŸ’‘ Hints (2)
  • β€’ The replacer function receives the matched substring as its first argument.
  • β€’ Convert with `Number(match)`, multiply, then convert back to `String`.