JS: String.prototype.replace

By Xah Lee. Date: . Last updated: .

Replace plain text (no regular expression)

str.replace(findStr, repStr)
  • Replace the first occurrence of findStr by repStr.
  • Return the new string.
  • No regex is used.
console.log("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.

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

Replace by regular expression

str.replace(regex_obj, repStr)
  • Replace regex_obj by repStr.
  • Return the new string.

If regex_obj has the regex flag g, 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.log("abc".replace(/./, "-"));
// -bc

// yes regex flag g, replace all occurrences
console.log("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.log(
  xresult === `
<img src="cat.jpg" alt="cat">
<img src="dog.jpg" alt="dog">
`,
);
str.replace(regex_obj, 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.log(
  xtext.replace(xrg, ff) === `
<img src="big_black_cat.jpg" alt="big black cat">
<img src="small_cat.jpg" alt="small cat">
`,
);

Replace All

To replace all occurrences, add regex flag g. (or use replaceAll)

"no no no".replace(/no/g, "yes") === "yes yes yes"

Regex Example

Using named capture:

// add alt attribute to a HTML image tag.

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.log(
 xb === `
<img src="cat.jpg" alt="cat">
<img src="dog.jpg" alt="dog">
`,
);

JavaScript. Regular Expression

JS String.prototype