JS: String.prototype.replaceAll

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2021)

Plain text replace

str.replaceAll(str1, repStr)
  • Replace all occurrences of string str1 by repStr. (No regex.)
  • Return a new string.
console.log("a.b.c".replaceAll(".", "-"));
// a-b-c
str.replaceAll(str1, repFunc)
  • Replace all occurrences of string str1 by a function repFunc. (No regex.)
  • Return a new string.

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

console.log("a.b.c".replaceAll(".", (x) => (x + x)));
// a..b..c

Regex replace

str.replaceAll(regex_obj, repStr)
  • Use regex to replace all occurrences.
  • regex_obj must have the regex flag g.
  • Return a new string.

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

/* replace all x followed by digits, to just digits */
console.log("x822 xddr x2156".replaceAll(/x(\d+)/g, "$1"));
// 822 xddr 2156
str.replaceAll(regex, repFunc)
  • The function repFunc's return value is used as the replacement string.

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

const xtext = `
alt="black_cat"
alt="dog"
alt="red-bird"
`;

/* find all alt attributes, replace lowline or hyphen by space */

const xoutput = xtext.replaceAll(/alt="([^"]+)"/g, (_matchedStr, zcap1) => "alt=" + '"' + zcap1.replace(/[-_]/g , " ") + '"');

console.log(xoutput ===
`
alt="black cat"
alt="dog"
alt="red bird"
`
);

JavaScript. Regular Expression