Basics of Javascript · String · replaceAll() (method)

Jakub Korch
Nerd For Tech
Published in
5 min readJun 11, 2021

This article is a transcript of my free youtube series about basics of web development. If you prefer watching over reading, feel free to visit my channel “Dev Newbs”.

Hello my fellow newbs! Today, we are going to have a little dejavú. We are going to talk about replaceAll() method, which is almost identical to replace() method. With a few exceptions of course. And you will find those in today’s episode.

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern is the first parameter and it can be either Regular Expression or simple string value. The replacement is a second parameter and it can be either a simple string value or it can be a function to be called for each match. If the Regular Expression does not contain a global flag, TypeError is thrown.

We will recycle the example number one from the previous article, to highlight subtle, but important differences between two sister methods.

const str = "The blue sweater itches. I'll wear a red t-shirt and a blue jeans.";let regExp = /blue/g;// PATTERN:     string
// REPLACEMENT: string
console.log("S -> S : " + str.replaceAll("blue", "green"));
// OUTPUT:
// S -> S : The green sweater itches. I'll wear a red t-shirt and // a green jeans.
// PATTERN: RexExp
// REPLACEMENT: string
console.log("RE -> S : " + str.replaceAll(regExp, "green"));
// OUTPUT:
// RE -> S : The green sweater itches. I'll wear a red t-shirt and // a green jeans.
// PATTERN: string
// REPLACEMENT: function
console.log
(
"S -> fn : " +
str.replaceAll
(
"blue",
(x) => {
return x.toUpperCase()
}
)
);
// OUTPUT:
// S -> fn : The BLUE sweater itches. I'll wear a red t-shirt and a // BLUE jeans.
// PATTERN: RexExp
// REPLACEMENT: function
console.log
(
"RE -> fn : " +
str.replaceAll(
regExp,
function (x)
{
return x.toUpperCase()
}
)
);
// OUTPUT:
// RE -> fn : The BLUE sweater itches. I'll wear a red t-shirt and a // BLUE jeans.

There are again four available combinations of “pattern” and “replacement” types of values.

In the first one, we are looking for a string “blue” and replacing it with string “green”. All the occurrences found are replaced. That is the most important difference between the two methods so far.

The second case is using a regular expression to find a match to replace with the simple string value of “green”. Since we are using the global flag within our regular expression, we will be replacing all of the matches, not just the first one.

The third case is a simple string “blue” being replaced by a function. Our function transforms any match to all uppercase characters. It does not matter that we are using a simple string as a pattern, all the matches are replaced.

The last — fourth case — is a regular expression match being replaced by function. We are replacing the lowercase version with an uppercase version.

If you forget to add the global flag into your regular expression, you get TypeError.

try {
let re = /(\w+)\s(\w+)/;
let fullName = 'John Smith';
let newstr = fullName.replaceAll(re, '$2, $1');
console.log(newstr); // Smith, John
}
catch(err){
console.log(err);
}
// OUTPUT:
// TypeError: String.prototype.replaceAll called with a non-global // RegExp argument at String.replaceAll (<anonymous>)
try {
let re = /(\w+)\s(\w+)/g;
let fullName = 'John Smith';
let newstr = fullName.replaceAll(re, '$2, $1');
console.log(newstr); // Smith, John
}
catch(err){
console.log(err);
}
// OUTPUT:
// Smith, John

TypeError informs us that we need to provide global RegExp. We make one by adding “g” at the end of the expression. Simple. And now it works.

There are few tricks that you can use when you provide a string as a parameter. Here are some of them in example 3.

let myList = 'John Adam Peter Herb';// $$ -> inserts "$"
myList.replaceAll("Peter", '$$')
// OUTPUT:
// John Adam $ Herb
// $& -> inserts "matched substring"
myList.replaceAll("Peter", '$& $& $&')
// OUTPUT:
// John Adam Peter Peter Peter Herb
// $` -> inserts "the portion of the string that precedes the matched substring"
myList.replaceAll("Peter ", '$`')
// OUTPUT:
// John Adam John Adam Herb
// $' -> inserts "the portion of the string that follows the matched substring"
myList.replaceAll(" Peter", "$'")
// OUTPUT:
// John Adam Herb Herb

You can output the “$” symbol by typing it twice. Or you can insert matched string multiple times in replacement. If that’s what you need, “$&” is the way to go. Sometimes you want the substring preceding the matched string. In that case, you can use “$`” and that’s what you get. Alternatively, you might want a substring following the matched string. In that case, you can use “$’” and you are all set. I am not completely sure you can use it in any way, but at least now you know you can do it. Yay!

The last example will show some tricks that you can do when you use a function as a replacement parameter.

let myBiggerList = 'John Adam Peter Herb Paul Marty';
let rgEx = /(P)([a-z]+)/gi;
myBiggerList.replaceAll
(
rgEx,
function
(
match,
p1,
p2,
offset,
str
)
{
console.log(match);
console.log(p1);
console.log(p2);
console.log(offset);
console.log(str);
console.log("");
}
);
// OUTPUT:
// Peter
// P
// eter
// 10
// John Adam Peter Herb Paul Marty
//
// Paul
// P
// aul
// 21
// John Adam Peter Herb Paul Marty

Based on the pattern you use, you get a set of parameters available to your replacement function. First one is always a matched string, followed by a varying number of matches for captured groups. Then you get an offset, which is basically an index value where the match starts. And lastly you get the original string.

You don’t need to use all of the parameters, but you need to keep in mind that they will be provided to your function in this order no matter what you actually name them.

As with the previous method, this was real fun. But we are at the end now anyways. Thank you for your undying attention and as usual I will see you next time.

--

--

Jakub Korch
Nerd For Tech

Web enthusiast, programmer, husband and a father. Wannabe entrepreneur. You name it.