JS: String.prototype.replace

By Xah Lee. Date: . Last updated: .

Plain text replace (and only first occurrence)

str.replace(findStr, repStr)
  • Replace the first occurrence of findStr by repStr.
  • Return the new string.
  • No regex is used.
console.assert(
 "a.b.c".replace(".", "-") === "a-b.c",
);
str.replace(findStr, repFunc)
  • Replace the first occurrence of findStr by the return value of function repFunc.
  • Return the new string.
  • No regex is used.

for repFunc spec, see JS: Regex Replace Function Args.

🟢 tip: if you want to replace all, use String.prototype.replaceAll

Regular expression replace

str.replace(regexObj, repStr)
  • Replace string matched by regexObj to repStr.
  • Return the new string.

If regexObj has the Regex Flag g (global), replace all occurrences, else just first occurrence.

In the replacement string repStr, {$1, $2, etc} refers to captured group. see JS: Regex Replace String Dollar Sign.

// Basic example of replace with regex

// no regex flag g, only first occurrence replaced
console.assert(
 "abc".replace(/./, "-") === "-bc",
);

// with regex flag g, replace all occurrences
console.assert(
 "abc".replace(/./g, "-") === "---",
);
/*
example of using replace with regex with captured groups.
add alt attribute to a HTML image
*/

const xtext = `
<img src="cat.jpg">
<img src="dog.jpg">
`;

// with regex flag g, replace all
const xresult = xtext.replace(
  /<img src="([-\w]+)\.jpg">/g,
  '<img src="$1.jpg" alt="$1">',
);

console.assert(
  xresult === `
<img src="cat.jpg" alt="cat">
<img src="dog.jpg" alt="dog">
`,
);
str.replace(regexObj, repFunc)

The function is called for each match. See JS: Regex Replace Function Args

/*
add a alt attribute to a HTML image tag, but convert any underscore to space.
for example
<img src="my_cat.jpg">
becomes
<img src="my_cat.jpg" alt="my cat">
*/

const ff = ((
  Ms,
  G1,
) => (`<img src="${G1}.jpg" alt="${G1.replace(/_/g, " ")}">`));

const xtext = `
<img src="big_black_cat.jpg">
<img src="small_cat.jpg">
`;

const xrg = /<img src="([-\w]+)\.jpg">/g;

console.assert(
  xtext.replace(xrg, ff) === `
<img src="big_black_cat.jpg" alt="big black cat">
<img src="small_cat.jpg" alt="small cat">
`,
);

Example. replace all

To replace all occurrences, add Regex Flag g (global).

🟢 tip: better is JS: String.prototype.replaceAll

console.assert(
 "no no".replace(/no/g, "yes") === "yes yes",
);

Example. regex with named capture

// add alt attribute to HTML image tags.

const xa = `
<img src="cat.jpg">
<img src="dog.jpg">
`;

// with regex flag g, replace all
const xb = xa.replace(
 /<img src="(?<imgName>[-\w]+)\.jpg">/g,
 '<img src="$<imgName>.jpg" alt="$<imgName>">',
);

console.assert(
 xb === `
<img src="cat.jpg" alt="cat">
<img src="dog.jpg" alt="dog">
`,
);

Symbol.replace property

🛑 warning: String.prototype.replace internally calls RegExp.prototype[Symbol.replace].

It means, you can customize it by adding a symbol property Symbol.replace function to the regex object.