Replace 'em all With ES2021
Pratik Chaudhari
Posted on November 23, 2020
The newly introduced
replaceAll()
method removes the need for using a regex
If you have ever worked with strings
in JavaScript, you know what a pain it is to replace all the matching substrings in a string!
Okay, maybe I'm being a little dramatic here, but it sure as hell wasn't something you could do easily as a novice.
For example, when I first started working with JavaScript
(I was fairly new to programming back then) and wanted to replace all the occurrences of a word in a string
, I just couldn't figure out how to do it by reading the replace()
method's documentation.
I wondered why I needed to use something so complicated as a regex to do something so simple as replacing all occurrences of a word in a string (I wasn't a big fan of regex
back then, and to be frank, I still am not).
Anyway, come ES2021, you won't need to use a regex
for the said operation!
That's because ES2021 has introduced a new (and a long-awaited) utility method for replacing all occurrences of a substring in a given string: replaceAll()
.
Let me walk you guys through an example to give you a better idea of what I'm talking about:
let aString = "I love Java. Java is very very easy to learn. Java's a very popular programming language"
let newString = aString.replaceAll("Java","JavaScript")
console.log(newString)
//I love JavaScript! JavaScript is very very easy to learn. JavaScript's a very popular programming language!
Here's a gif depicting the execution of the above code in Chrome's console (Yeah, Chrome has already shipped this feature, and so have the other browsers):
The replaceAll()
method keeps the original string intact and returns a new string.
Make note here that replaceAll()
makes a case-sensitive comparison while searching for the target substring.
If I were to replace the uppercase 'J' of 'Java' with a lowercase 'j', replaceAll()
won't replace it, and the new string will resemble the old one.
Here's another gif to show you what I mean:
Like its cousin replace()
, replaceAll()
also allows you to specify a regex in place of the target substring (i.e., the substring to be replaced), but I think doing so would defeat the entire purpose of using replaceAll()
.
If you'd like to know more about replaceAll()
, feel free to go through its MDN documentation.
That's all for this article, folks!
Hope you enjoyed reading this piece and learned something new.
Posted on November 23, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.