JavaScript: String.prototype.replace

By Xah Lee. Date: . Last updated: .

Original string is not changed by this function.

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: JavaScript: Regex Replacement Function Arguments

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

If regexObj has the RegExp Flag g, replace all occurrences, else just first occurrence.

In the replacement string repStr, {$1, $2, etc} refers to captured group. [see JavaScript: Regex Replacement String Dollar Sign Sequence]

// Basic example of replace with regex

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

// yes global 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 x1 = `
<img src="cat.jpg">
<img src="dog.jpg">
`;

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

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

The function is called for each match. See: JavaScript: Regex Replacement Function Arguments

/*
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, use regex with the global flag g. (or use replaceAll)

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

Regex Example

Using named capture:

// add alt attribute to a HTML image tag.

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

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

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

JavaScript Regular Expression


BUY ΣJS JavaScript in Depth