JavaScript: String.prototype.replace

By Xah Lee. Date: . Last updated: .
str.replace(str1, str2)
Replace the first occurrence of str1 by str2. Return the new string. If no match, the original string is returned. No regex is used. Original string is not changed.
str.replace(regex, str_or_func)
Return the new string. If no match, the original string is returned. str_or_func can be a string or function. If string, {$1, $2, etc} refers to captured group.

If function, its return value will be used as the replacement string. The function is called for each match. The function receive variable count of args, in this order:

  • matched substring.
  • capture group 1. (named capture is also a numbered capture)
  • capture group 2, etc.
  • offset position (integer), of the matched substring in the target string.
  • Whole target string.
  • A object of named capture groups. Key is capture name, value is corresponding substring. (or undefined if none).
Original string is not changed.

[see Regex Functions]

[see RegExp Syntax]

When using regex, the following dollar sign sequence have special meaning in the replace string.

$n
nth captured match. (n is a positive integer less than 100)
$<name>
refers to named capture name.
$&
the matched string.
$`
the string before the matched string.
$'
the string after the matched string.
$$
literal dollar sign character.

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"); // true

No Regex Example

console.log( "a.b.c".replace(".", "9") === "a9b.c" ); // true

Regex Example

Basic example:

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

// yes global flag g, replace all occurrences
console.log("abc".replace(/./g, "9") === "999"); // true

With captured group:

// 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="([-\w]+)\.jpg">/g,
  '<img src="$1.jpg" alt="$1">',
);

console.log(x2);
/* [
<img src="cat.jpg" alt="cat">
<img src="dog.jpg" alt="dog">
] */

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">
] */

With a function as second argument:

// 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 = ((
  whole,
  group1,
) => (`<img src="${group1}.jpg" alt="${group1.replace(/_/g, " ")}">`));

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

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

console.log(txt.replace(regex, ff));
/* [
<img src="big_black_cat.jpg" alt="big black cat">
<img src="small_cat.jpg" alt="small cat">
] */

Show arguments received by function:

// show arguments received by function

const ff = ((...args) => {
  console.log(args);
  return "3";
});

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

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

console.log(txt.replace(regex, ff));

/* [
output

[
  '<img src="big_black_cat.jpg">',
  "big_black_cat",
  1,
  '\n<img src="big_black_cat.jpg">\n<img src="small_cat.jpg">\n',
  { imgName: "big_black_cat" }
]
[
  '<img src="small_cat.jpg">',
  "small_cat",
  31,
  '\n<img src="big_black_cat.jpg">\n<img src="small_cat.jpg">\n',
  { imgName: "small_cat" }
]

3
3
] */
JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

String

prototype