How do I replace all occurrences of a string in JavaScript?

Often web developers need to be able to replace all occurrences of string on their website or application. You can easily do this using JavaScript. In this article, we will learn the different solutions to replace one or more occurrences of a substring in a given string, using plain JavaScript.

How do I replace all occurrences of a string in JavaScript?

Here are the different ways to replace all occurrences of a substring in JavaScript. They can be used to replace multiple occurrences of a single character, word, phrase or expression.

1. Using ReplaceAll

Every JavaScript string (literal or variable) supports replaceAll() method that allows you to replace all occurrences of substring in JavaScript. Here is its syntax.

string.replaceAll(new_substring, old_substring)

In the above function, we need to provide two arguments – the substring or pattern to be replaced and the new substring to take its place. ReplaceAll() will return a new string with replacement. It will not modify the original string. Here is an example to illustrate this.

var a= 'good morning, good night';
console.log(a.replaceAll('good','hello')); // output is 'hello morning, hello night'
console.log(a); // output is 'good morning, good night'

If you specify a string for replacement, then replaceAll() will only replace the exact match of that substring. If you specify a regular expression instead of a string, then it will replace all variations of that regular expression in the original string. This is useful for complex matches. But you need to enclose the regular expression within /…/g

var a= 'good morning, good night';
console.log(a.replaceAll(/good/g,'hello'));
console.log(a);

If you do not mention the regular expression within /…/g then you will get the following error.

TypeError: String.prototype.replaceAll called with a non-global RegExp argument

By default, replaceAll() function does a case-sensitive replacement. If you want to do a case-insensitive replacement, then use /…/gi. The g flag specifies that it is a regular expression, and i flag stands for case insensitive replacement.

var a= 'good morning, Good night';
console.log(a.replaceAll(/good/gi,'hello')); // output is hello morning, Good night

Please note, if you are using older web browsers then it may not support replaceAll() function. In such cases, you can use either of the following methods.

2. Using Replace

The replace() method is supported by older web browsers but it only replaces the first occurrence of a given substring, by default.

var a= 'good morning, good night';
console.log(a.replace('good','hello')); // output is hello morning, good night

If you want to replace all occurrences of a substring in a string, then you need to provide a regular expression, instead of a literal string. You can do this by enclosing the substring within /…/g as shown.

var a= 'good morning, good night';
console.log(a.replace(/good/g,'hello')); // output is hello morning, hello night
console.log(a); // output is good morning, good night

Like replaceAll() function, it will not modify the original string but only return modified copy of the original string. If you want to modify the original string, then you need to re-assign the result of replace() function to the same string variable.

Like replaceAll() function, replace() function also does a case sensitive replacement, by default. If you want to do a case insensitive find and replace, then you need to enclose the original substring within /…/gi where g flag means regular expression and i flag means case insensitive match.

var a= 'good morning, Good night';
console.log(a.replace(/good/gi,'hello')); // output is hello morning, hello night

3. Using Split & Join

This is a little complicated solution but mentioned here for the sake of completeness. In this approach, we use split() function to split the original string into an array of substrings. Then we use join() function to combine the array items into a single string.

The split function basically splits a string into an array of substrings, based on a separator value provided as an argument. In our case, we pass the substring to be replaced as the separator for split function.

var a= 'good morning, good night';
var arr = a.split('good');
console.log(arr); // output is [ '', ' morning, ', ' night' ]

On the other hand, join function allows you to concatenate the different items of an array, into a single string. While doing so, you may or may not specify a character or substring to join the items. We will call join function on the result of above split function, and specify the replacement substring to be used during concatenation of array elements.

var b= arr.join('hello');
console.log(b); // output is hello morning, hello night

Conclusion

In this article, we have learnt different ways to replace all occurrences of substring in a string, using JavaScript. Among them, using replaceAll() is the simplest and best solution for this purpose. If you are using older web browsers, then you can use replace() function. They are both supported by string literals as well as string variables. By default, both replaceAll() and replace() find and replace exact match of the substring. If you want to do a complex match then you need to use regular expressions instead of literal strings.

Also read:

How to Check Whether String Contains Substring in JavaScript
How to Remove Elements from JavaScript Array
How to Detect Invalid Date in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *