Tutorials Tonight's Logo

Replace All string JavaScipt With 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


replace All String JavaScipt

To replace all occurrences of a word or character in a string use the replaceAll() method in JavaScipt.

The replaceAll() method accepts a substring or regex(regular expression) to match words or characters 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"

const str = "to do or not to do.";
const pattern1 = "do"; // string
console.log(str.replaceAll(pattern1, "code"));
// to code or not to code.

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

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

replace string javascript example

Note: When using regex to find matching substring in 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:

string.replaceAll(substr | regexp, new_string | 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 use 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 string or characters using the replaceAll method.

# Example 1: Matching by substring

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

Example

const str = "to do or not to do.";
const pattern = "d";
console.log(str.replaceAll(pattern, "g"));
// 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

const str = "To-do_or_not_to-do.";
const pattern = /[_-]/g;
console.log(str.replaceAll(pattern, " "));
// 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 substrings from the string with another new 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

let 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.";
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.

const str = "to do or not to do.";
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.

const str = "to do or not to do.";
let newString = str.replaceAll(/do/g, "Sleep");
console.log(newString);
// to Sleep or not to Sleep.


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 | 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 use 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 replacement function:

Arguments Description
match This is the part of the string that matches the pattern
p1, p2, ... The string found by parenthesized capturing group in the string. 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 newString = str.replaceAll(pattern, (match, p1, offset, string) => {
  return `(${match}) => Sleep \n(capturing ${p1}) at index ${offset} in (${string})\n`
})
console.log(newString);
▶ 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.


Points to remember:

  1. The replaceAll method uses a string or regular expression to match a part of the string and replace it with another new string.
  2. The replaceAll method also accepts a replacement function as the second parameter where the method uses its return value of the function as a new string.
Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.