JavaScript: String.prototype.replaceAll
New in JS2021.
Original string is not changed by this function.
str.replaceAll(str1, repStr)
-
Replace all occurrences of string str1 by repStr. (No regex is used.)
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 is used.)
Return a new string.
The function is called for each match. See: JavaScript: Regex Replacement Function Arguments
const ff = ((x) => { return x + x; }); console.log( "a.b.c".replaceAll(".", ff) === "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 JavaScript: Regex Replacement String Dollar Sign Sequence]/* replaceAll basic example */ console.log( "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: JavaScript: Regex Replacement Function Arguments
/* 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
- RegExp Tutorial
- RegExp Functions
- RegExp Syntax
- RegExp Flags
- Replacement String Dollar Sign Sequence
- Replacement Function Arguments