Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

String.prototype.replace — replacing text

replace() returns text with matches replaced, without changing the original. Learn the difference between string and regular-expression searches, and between replacement templates and replacement functions.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

text.replace(searchValue, replaceValue)

String.prototype.replace with a plain string or standard RegExp returns a new string; the original remains unchanged. No match means unchanged content is returned. This is an ECMAScript language API, not a browser API.

A string searchValue is literal and replaces only the first occurrence; an empty string matches at the beginning. A standard RegExp without g replaces at most one match; with g, it replaces all matches found. An object with a [Symbol.replace] method can define custom behavior, including the result.

A string replaceValue interprets $$ as $, $& as the whole match, and $1 as the first existing capturing group. A replacement function receives the match, then captured groups, the index, and the input string; named groups add a final groups object. The index counts UTF-16 code units. The function result is converted to a string, but $ sequences are not interpreted.

The example compares first-only replacement, global replacement, a capture reference, and a literal function result. Printing text also checks that the original remains unchanged.

Examples

const text = "cat cat";
console.log(text.replace("cat", "dog"));
console.log(text.replace(/cat/g, "dog"));
console.log(text.replace(/(cat)/g, "[$1]"));
console.log(text.replace(/cat/g, () => "$&"));
console.log(text);

Result

dog cat
dog dog
[cat] [cat]
$& $&
cat cat

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources