JS: String.prototype.replaceAll
(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
- JS: Regular Expression Tutorial
- JS: Regular Expression Functions
- JS: Create Regex Object
- JS: Regular Expression Syntax
- JS: Regular Expression Flags
- JS: Regex Replace String Dollar Sign
- JS: Regex Replace Function Args
- JS: RegExp (class)
- JS: RegExp Constructor
- JS: RegExp.prototype
- JS: String.prototype.search
- JS: String.prototype.match
- JS: String.prototype.matchAll
- JS: String.prototype.replace
- JS: String.prototype.replaceAll
- JS: RegExp.prototype.test
- JS: RegExp.prototype.exec