Single literal substitution
Replace a known literal prefix or token once.
JavaScript · Function
String.prototype.replace() returns a new string with matching text replaced. String patterns replace only the first occurrence; use a global regular expression or replaceAll() for all occurrences.
Call replace() on a string with a string or pattern to search and a string or callback to generate replacement text. It returns a new string, leaving the original unchanged; a string pattern affects only its first occurrence, while a regular expression with the g flag can replace every match.
replace(pattern, replacement)| Name | Type | Description |
|---|---|---|
pattern | string | RegExp | object | The search value: a string, a regular expression, or an object providing Symbol.replace; values without that method are converted to strings. |
replacement | string | function | Replacement text, or a function called for each match whose return value supplies the replacement text. |
A new string with one, some, or all matches of the pattern replaced by the specified replacement.
, and $' to insert special text.const input = "2024-07-15";
const formatted = input.replace(/^(\d{4})-(\d{2})-(\d{2})$/, "$2/$3/$1");
console.log(formatted); // "07/15/2024"A regular expression captures the date parts, and replacement tokens insert them in month/day/year order.
Replace a known literal prefix or token once.
Transform every match with regular expressions and capture groups.
Generate replacement text from match data.
replace(pattern, replacement) returns a new string with matching text substituted. The pattern may be a string or an object implementing Symbol.replace, and the replacement may be a string or function.
Follow-up: How can every occurrence of a literal substring be replaced? Use replaceAll(), or use a regular expression with the global g flag.
A string pattern is searched only once, so only its first occurrence is replaced. A global regular expression can match multiple occurrences.
Follow-up: What happens if the original string is not assigned the result? The source remains unchanged, because strings and this method do not mutate it.
A replacement function is called for each match, and its return value becomes that match's replacement text. This is useful when replacement content depends on the matched text or captures.
Follow-up: How can captured groups be used? Define capturing groups in the regular expression and read the corresponding callback arguments, then construct the returned replacement.
String.prototype.replaceAll()RegExp.prototype[Symbol.replace]()Symbol.replaceString.prototype.match()String.prototype.matchAll()