JS: String.prototype.replaceAll
New in JS2021.
str.replaceAll(str1, repStr)
-
- Replace all occurrences of string str1 by repStr. (No regex is used.)
- Return a new string.
"a.b.c".replaceAll(".", "-") === "a-b-c"
str.replaceAll(str1, repFunc)
-
- Replace all occurrences of string str1 by a function repFunc. (No regex is used.)
- Return a new string.
The function is called for each match. See: JS: Regex Replace Function Args
"a.b.c".replaceAll(".", ((x) => (x + x))) === "a..b..c"
str.replaceAll(regexObj, repStr)
-
- Use regex to replace all occurrences.
- regexObj must have the RegExp 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〕/* replaceAll basic example */ "xy x1 x2".replaceAll(/x(\d+)/g, "y$1") === "xy y1 y2"
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
/* example of RegExp replace, using function as replacement. add a alt attribute to a HTML image tags, but convert any lowline char to space. for example <img src="my_cat.jpg"> become <img src="my_cat.jpg" alt="my cat"> */ const xtext = ` <img src="black_cat.jpg"> <img src="dog.jpg"> <img src="red-bird.jpg"> `; const xrg = /<img src="([-\w]+)\.jpg">/g; const fRep = (( Ms, C1, ) => (`<img src="${C1}.jpg" alt="${C1.replace(/_/g, " ")}">`)); const yy = xtext.replaceAll(xrg, fRep); console.log( yy === ` <img src="black_cat.jpg" alt="black cat"> <img src="dog.jpg" alt="dog"> <img src="red-bird.jpg" alt="red-bird"> `, );
Examples
With captured group:
/* add alt attribute to a HTML image tags */ const xx = ` <img src="cat.jpg"> <img src="dog.jpg"> <img src="mouse.jpg"> `; const yy = xx.replaceAll( /<img src="([-\w]+)\.jpg">/g, '<img src="$1.jpg" alt="$1">', ); console.log( yy === ` <img src="cat.jpg" alt="cat"> <img src="dog.jpg" alt="dog"> <img src="mouse.jpg" alt="mouse"> `, );
JavaScript, Regular Expression
- JS: RegExp Tutorial
- JS: Regex Functions
- JS: RegExp Syntax
- JS: RegExp Flag
- JS: Regex Replace String Dollar Sign
- JS: Regex Replace Function Args
- JS: RegExp Object
- 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