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

String.prototype.replace() β€” no match returns original

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

If searchValue is not found, .replace() returns the original string unchanged.

Challenge: Implement safeReplace(str, from, to) that replaces from with to, or returns str if not found.

safeReplace('hello', 'xyz', '!!!')  // β†’ 'hello'
safeReplace('hello', 'ell', 'ELL') // β†’ 'hELLo'
πŸ’‘ Hints (1)
  • β€’ `.replace()` never throws β€” it just returns the original string if nothing matched.