DEV Community

Cover image for How to Replace All Occurrences of a String
Boyan Iliev
Boyan Iliev

Posted on • Originally published at devdojo.com on

How to Replace All Occurrences of a String

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!';
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

replaceAll is actually a relatively recent addition to JS and probably is not the main method used in a lot of JS libraries - and certainly is not the only method. The original way to do a 'replace all' is just with replace - the following would be the same as your example:

let intro = 'My! n!ame! i!s Bo!yan!';
let newIntro = intro.replace(/\!/g, '');
Enter fullscreen mode Exit fullscreen mode

Note the g at the end of the regular expression - making it a global match on the string

Collapse
 
boiliev profile image
Boyan Iliev

This is great to know. Thanks for the feedback!