Replace Occurrences of a Substring in String with JavaScript

Introduction

Replacing all or n occurrences of a substring in a given string is a fairly common problem of string manipulation and text processing in general. JavaScript offers a few ways to get this done fairly easily.

In this tutorial, we'll cover some examples of how to replace occurrences of a substring in a string, using JavaScript.

We'll be working with this sentence:

The grey-haired husky has one blue and one brown eye.

We'll want to replace the word "blue" with "hazel".

replace()

The simplest way to do this is to use the built-in replace() function. It accepts a regular expression as the first argument, and the word(s) we're replacing the old ones with as the second argument. Alternatively, it accepts a string as the first argument too.

Since strings are immutable in JavaScript, this operation returns a new string. So if we want to make the changes permanent, we'll have to assign the result to a new string on return.

Let's see how we can use the function:

const regex = /blue/;

let originalStr = 'The grey-haired husky has one blue and one brown eye.';
let newStr = originalStr.replace(regex, 'hazel');

console.log(originalStr);
console.log(newStr);

Here, we've used a regular expression literal instead of instantiating a RegExp instance. This results in:

The grey-haired husky has one blue and one brown eye.
The grey-haired husky has one hazel and one brown eye.

Alternatively, we could've defined the regular expression as:

let regex = new RegExp('blue');

The result would've been the same. The difference between a regex literal and a RegExp object is that literals are compiled ahead of execution, while the object is compiled at runtime.

The former is more efficient if the regular expression stays constant, while the latter is typically used if the regex can be dynamic, such as an expression defined by the user.

To perform a case-insensitive replacement, you can pass the i flag to the regular expression:

const regex = /blue/i;

let originalStr = 'The grey-haired husky has one Blue and one brown eye.';
let newStr = originalStr.replace(regex, 'hazel');

console.log(originalStr);
console.log(newStr);

Now, this results in:

The grey-haired husky has one Blue and one brown eye.
The grey-haired husky has one hazel and one brown eye.

Without the i flag, Blue wouldn't match to the /blue/ regex.

Finally, you can use a string instead of a regular expression:

let originalStr = 'The grey-haired husky has one blue and one brown eye.';
let newStr = originalStr.replace('blue', 'hazel');

console.log(originalStr);
console.log(newStr);

This also results in:

The grey-haired husky has one blue and one brown eye.
The grey-haired husky has one hazel and one brown eye.

Note: This approach works only for the first occurrence of the search string. To replace all occurrences, you can use the replaceAll() function.

If we update the string:

let originalStr = 'The grey-haired husky a blue left eye and a blue right eye.';
let newStr = originalStr.replace('blue', 'hazel');

The result would be:

The grey-haired husky has a blue left eye and a blue right eye.
The grey-haired husky has a hazel left eye and a blue right eye.

Notice how only the first occurance of "blue" is replaced, but not the second.

Note that we actually can replace all instances of a string when using the regex approach and .replace(). To make this happen, we'll want to use the g regex flag, which stands for "global". This matches all instances in a string. For example:

const regex = /blue/g;

let originalStr = 'The grey-haired husky a blue left eye and a blue right eye.';
let newStr = originalStr.replace(regex, 'hazel');

console.log(originalStr);
console.log(newStr);
The grey-haired husky has a blue left eye and a blue right eye.
The grey-haired husky has a hazel left eye and a hazel right eye.

replaceAll()

As of August 2020, as defined by the ECMAScript 2021 specification, we can use the replaceAll() function to replace all instances of a string.

It accepts a string we're searching for and a string we'd like to replace it with:

let originalStr = 'The grey-haired husky has a blue left eye and a blue right eye.';
let newStr = originalStr.replaceAll('blue', 'hazel');

console.log(originalStr);
console.log(newStr);

This results in:

The grey-haired husky has a blue left eye and a blue right eye.
The grey-haired husky has a hazel left eye and a hazel right eye.

Now all instances of the search word have been replaced.

split() and join()

If replaceAll() isn't supported in your JavaScript runtime, you can use the trusty old split() and join() approach:

let originalStr = 'The grey-haired husky has a blue left eye and a blue right eye.';
let newStr = originalStr.split('blue').join('hazel');

console.log(originalStr);
console.log(newStr);

The split() function splits the string into an array of substrings on the given string - 'blue'. Upon splitting, we have an array of:

["The grey-haired husky has a ", " left eye and a ", " right eye."]

Then, when se use join() with a string, we join it back into the original sentence, with the string passed to the function inserted in the breaks.

Now, we're left with all occurrences of the original string replaced with a new one:

The grey-haired husky has a blue left eye and a blue right eye.
The grey-haired husky has a hazel left eye and a hazel right eye.

Note: While this approach does work, it is not recommended for use if one of the other previously explained methods are available to use. The reason for this is that the purpose behind this approach is not as obvious at first-glance, and therefore it makes the code less readable.

Conclusion

In this article, we've gone over a few examples of how you can replace occurrences of a substring in a string, using JavaScript.