transformation
String.prototype.replace
Returns a new string with the first match of pattern replaced. Pattern can be a string (only the first occurrence) or a RegExp (all occurrences when the g flag is set).
str.replace(pattern, replacement) Parameters
| Parameter | Purpose |
|---|---|
| pattern | String or RegExp to match |
| replacement | Replacement string ($1, $&, $<name>) or function returning a string |
Examples
console.log('foo foo'.replace('foo', 'bar')); Prints 'bar foo' (only first match)
console.log('foo foo'.replace(/foo/g, 'bar')); Prints 'bar bar'
console.log('John Smith'.replace(/(\w+)\s(\w+)/, '$2 $1')); Prints 'Smith John'
console.log('abc123'.replace(/\d+/, m => m.length)); Prints 'abc3'
Gotcha
A string pattern only replaces the first match — use replaceAll or a /g RegExp for all. Strings are immutable; the original is unchanged.
Related methods
String.prototype.replaceAll
Returns a new string with every occurrence of pattern replaced. Added in ES2021; if pattern is a RegExp it must have the g flag or replaceAll throws TypeError.
String.prototype.match
Runs a regular expression against the string and returns match information. With the g flag it returns an array of all match strings; without it, an exec-style array with capture groups, index, and input (or null).
String.prototype.split
Divides the string into an array of substrings using separator (string or RegExp). With no separator the whole string is returned as a one-element array; with '' each UTF-16 code unit becomes an element.
String.prototype.toUpperCase
Returns a new string with all characters converted to upper case using the Unicode default case mapping. Locale-insensitive — use toLocaleUpperCase for language-specific rules (e.g. Turkish i).
String.prototype.toLowerCase
Returns a new string with all characters converted to lower case using Unicode default case mapping. For locale-specific behavior use toLocaleLowerCase.