Replace All string JavaScript: replaceAll() Method


In this tutorial, you will learn how to replace all a part of a string with another string in JavaScript using replace() method with various examples

Quick Solution

For a quick solution and learning of how to replace all a part of a string with another string in JavaScript, you can check the following code:

Example

// replaceAll() method is used to replace all matches
// in a string with another string.

// 1. Replace "o" with "*" in "Hello World"
var str = "Hello World";
var newStr = str.replaceAll("o", "*");
console.log(newStr); // "Hell* W*rld"

// 2. Replace l and e with * (using regex)
var str = "Hello World";
var newStr = str.replaceAll(/[le]/g, "*");
console.log(newStr); // H***o Wor*d

// 3. call a function for each match
var str = "Hello World";
var newStr = str.replaceAll(/o/g, function(match, index, originalText) {
  return "*" + match + "*";
});
console.log(newStr); // Hell*o* W*o*rld

replace All String JavaScript

To replace all occurrences of a match (word or random string) in a string use the replaceAll() method in JavaScript.

The replaceAll() method uses a string or regex(regular expression) to match a pattern within the string and replace it with another new string.

You can either directly specify the new string as the second parameter of the method or pass a function as the second parameter whose return value is used as a new string.

Let's see a basic example to start off, further in this section we will see more examples to explore the method and its arguments.

Example: Replacing all occurrences of "do" with "code"

// replace all string javascript
var str = "to do or not to do";

// using string
var newStr = str.replaceAll("do", "code");
console.log(newStr); // to code or not to code

// Using regex
var newStr = str.replaceAll(/do/g, "code");
console.log(newStr); // to code or not to code
Try It

In the above example, you can see whether you use a string or a regex to match the string the replaceAll method replaces all the occurrences of matching within the calling string.

replace string javascript example

Note: When using regex to find matching substring in the replaceAll() method using the /g flag with regex is necessary otherwise it will throw a TypeError ("replaceAll must be called with a global RegExp").


Syntax of replaceAll method

The syntax of replaceAll() method is as follows:

str.replaceAll(substr, new_string);
str.replaceAll(regexp, new_string);

str.replaceAll(substr, function);
str.replaceAll(regexp, function);
  1. substr - The substring that is to be replaced by the new_string. It is not treated as a regular expression but just as a literal string.

  2. regexp - The regular expression used to find the match within the string and replace it with the new_string.

  3. new_string - The replacement string that replaces the matched pattern.

  4. function - The function as a second parameter that is invoked for every match of the pattern in the string. The method uses the return value of the function as a new string. The replacement function is discussed in detail below.

Note: The replaceAll method doesn't change the original string it creates a new string by replacing the necessary substring and return it.


Replace All String Examples

Let's see some example to replace strings or characters using the replaceAll method.

# Example 1: Matching by string

The example below replaces all the characters "d" with "g" using the string "d" as a matching string in the replaceAll method.

Example

var str = "to do or not to do";

// replace "d" with "g"
var newStr = str.replaceAll("d", "g");
console.log(newStr); // to go or not to go
Try It

# Example 2: Replacing all underscores and dashes with space

The following example uses a regular expression to find all underscores (_) and dashes (-) and replace all by space ( ) using the replaceAll method.

Example

var str = "To-do_or_not_to-do";

// replace all underscores and dashes with space
var newStr = str.replaceAll(/[_-]/g, " ");
console.log(newStr); // To do or not to do
Try It

# Example 3: Channing replaceAll method

Suppose you have a string and you want to replace 2 more than 2 different matches from the string.

So the basic idea to do this would be to replace the matchings one by one and assign the return value every time to the original string, as shown in the example below.

Example

var str = "To do or not to do.";
str = str.replaceAll(/do/gi, 'code'); // replace all do with code
str = str.replaceAll(/to/gi, 'love'); // replace all to with love
console.log(str);
// love code or not love code.
Try It

Instead of replacing and assigning return value one by one you can directly chain the replaceAll() method and do this in a single line of code.

Example

let str = "To do or not to do.";

// chaining the replaceAll() method
str = str.replaceAll(/do/gi, "code").replaceAll(/to/gi, "love");
// replace all do with codeand replace all to with love
console.log(str);
// love code or not love code.
Try It

Non-global regex Error Throw

Using global flag (/g) is necessary with the replaceAll method otherwise it throws an error.

var str = "to do or not to do.";

// no g flag
str.replaceAll(/do/, "Sleep"); // Throw Error

The above code throws an error, so added a global flag to the regex in the example below a this works.

Example

const str = "to do or not to do.";

// always use g flag with replaceAll Methods
let newStr = str.replaceAll(/do/g, "Sleep");
console.log(newStr);

Using a replacement function

In the above examples, you have seen and used a direct string to replace the matching substring in the replaceAll method. But you can use a replacement function as a second parameter to the method whose return value is used as a new string to replace the matching substrings.

Here is how you can add a replacement function to the method.

str.replaceAll(substr, replacement_function);
str.replaceAll(regex, replacement_function);

The replacement function is invoked after a match has been performed within the string. If there are multiple matches then the method the replacement function will be invoked for each match.

The return value of the replacement function is used as a new string to replace the matching string, which can be the same or different for each match.

Example

const str = "to do or not to do.";
const pattern = /do/g;
function replacer() {
  return "Sleep";
}
console.log(str.replaceAll(pattern, replacer));
// to Sleep or not to Sleep.
Try It

In the above example, the replacement function is invoked every time a match is performed and uses the return value as a new string to replace all the matches.

Let's now understand the replacer function in detail.

Syntax of replacement function

function replacer(match, p1, p2, ..., offset, string) { }

Following are the arguments of the replacement function:

Arguments Description
match This is the part of the string that matches the pattern
p1, p2, ... The string is found by parenthesized capturing group in the string. This means p1 will be the first capture of capturing group, p2 will be the second, and so on.
offset This is the index value of matched substring or capturing group.
string The string that calls the method

The following example shows the matches and the replaced value for the match using the replacement function.

Showing match using replacement function

const str = "to do or not to do.";
const pattern = /do/g;
function replacer(match) {
  return `(${match}) => Sleep`;
}
console.log(str.replaceAll(pattern, replacer));
// to Sleep or not to Sleep.

The example below shows the captures of the capturing group by the regex used in the method.

Example

const str = "to do or not to do.";
const pattern = /d(o)/g;
function replacer(match, p1) {
  return `(${match}) => Sleep \n(capturing ${p1})\n`;
}
console.log(str.replaceAll(pattern, replacer));

The example below shows the captures offset of the capturing group within the string.

Example

const str = "to do or not to do.";
const pattern = /d(o)/g;
function replacer(match, p1, offset) {
  return `(${match}) => Sleep \n(capturing ${p1}) at index ${offset}\n`;
}
console.log(str.replaceAll(pattern, replacer));

The example below uses all the parameters of the replacement function.

Example

const str = "to do or not to do.";
const pattern = /d(o)/g;
function replacer(match, p1, offset, string) {
  return `(${match}) => Sleep \n(capturing ${p1}) at index ${offset} in (${string})\n`;
}
console.log(str.replaceAll(pattern, replacer));
Try It

Array Function As Replacement Function

You can use also the array function as a replacement function for the replaceAll() method both anonymous function or named function.

Example

const str = "to do or not to do.";
const pattern = /d(o)/g;
const newStr = str.replaceAll(pattern, (match, p1, offset, string) => {
  return `(${match}) => Sleep \n(capturing ${p1}) at index ${offset} in (${string})\n`
})
console.log(newStr);
Try It

Alternate method: Using Split and Join Method To Replace String

You would be familiar with the split and join method of the array. The split method splits any string and put it in the array when it finds a certain substring init, while the join method joins the members of an array into a string by adding a string between 2 members of the array.

We can use this combined to create the same effect as the replaceAll method. Split your string at the matching string and join the array by passing the new string as a separator in the join method. See the example below.

Example

const str = "to do or not to do.";
const subStr = "do";
const replaceBy = "Sleep";
const newStr = str.split(subStr).join(replaceBy);
console.log(newStr);
Try It

The above example split the string using the split method when it finds "do" in the string and join them using "Sleep" as a separator in the join method.


Conclusion

To replace all the occurrences of a string or any pattern use replaceAll() method in javascript. We have seen this method in detail in this guide.