Introduction
One of the main data types in JavaScript is strings
. These data types are used for storing and manipulating text. And luckily for us, there are quite a few methods that help us in manipulating these data types.
These methods are one of the many built-in methods of JavaScript. This is because JS has some built-in objects. Some of them are: Array
, Math
and String
. And for each object, some properties and methods are associated with them.
In this post we are going to see How to Replace All Occurrences of a String with the replaceAll()
method.
replaceAll()
Method
In order to use this method, we first have to create our string. Let's add randomly !
inside this strong so that we can remove it.
let intro = 'My! n!ame! i!s Bo!yan!';
Now to remove it, we have to write the strings name, then add the replaceAll
method next to it, and pass in the first argument which element we want to be replaced or removed. An important thing is to remember that you have to save the new string into a new variable. It should look something like this:
let newIntro = intro.replaceAll('!', '')
console.log(newIntro);
<- My name is Boyan
Now if you want to replace the elements, just pass in the second argument as what you want it replaced with. Let's replace the whitespace with -
.
let newerIntro =newIntro.replaceAll(' ', '-');
console.log(newerIntro)
<- My-name-is-Boyan
Conclusion
This is pretty much it to the replaceAll()
method. It is the main method used, if not the only method, that replaces all occurrences of a string.
I hope that this post has helped you and I would love to hear some feedback in the comments below.
Comments (0)