DEV Community

Vladymir Adam
Vladymir Adam

Posted on

Using replace() and replaceAll() in JavaScript

In this tutorial, we're going to see how to use the methods replace() and replaceAll() in javascript.

Both methods are part of the String object. that means you can invoke them on strings. Let's start with replace().

The replace() method can be used to search from a string, a specific character or a substring that matches a pattern that you provide in order to replace it by another character or a new substring. The method takes 2 arguments, the first one will be the pattern and the second one will be the newsubstring.

replace('pattern','newsubstring');
Enter fullscreen mode Exit fullscreen mode

The pattern can be a string or a regular expression.

let's put an example:

let str = 'cars are fast';
let newstr = str.replace('cars', 'planes');
console.log(newstr);
//the output will be:planes are fast

Enter fullscreen mode Exit fullscreen mode

There are 2 important points to mention:
First, the method return a new string, it doesn't modify the original one.

let str = 'cars are fast';
let newstr = str.replace('cars', 'planes');
console.log(newstr);
//the output will be:planes are fast
console.log(str); // str is still: cars are fast
Enter fullscreen mode Exit fullscreen mode

Second, when the pattern is a string it will return the first occurence it finds.

let str = 'cars are fast but, some cars are really fast';
let newstr = str.replace('cars', 'planes');
console.log(newstr);
/**
 * The output will be: 
 * planes are fast but, some cars are really fast
 */

Enter fullscreen mode Exit fullscreen mode

Now, let's see with a regular expression

let str = 'cars are fast but, some cars are really fast';
let newstr = str.replace(/cars/g, 'planes');
console.log(newstr);
/**
 * The output will be: 
 * planes are fast but, some planes are really fast
 */
Enter fullscreen mode Exit fullscreen mode

The letter g in the regular expression is for global, it makes the function searches for all the occurence.

For more details about how to use regular expression visit this guide.

For the replaceAll(), as the name suggest it will look for all the occurence that match the pattern to replace them by the newsubstring. And as the replace(), it will return a new string with the changes.

let str = 'cars are fast but, some cars are really fast';
let newstr = str.replaceAll('cars', 'planes');
console.log(newstr);
/**
 * The output will be: 
 * planes are fast but, some planes are really fast
 */
Enter fullscreen mode Exit fullscreen mode

I hope this will help you have a quick understanding of how to use replace() and replaceAll() in JavaScript.

Top comments (0)