How to Replace All Occurrences of a Word in a JavaScript String?

Learn how to replace multiple instances of the specified string in JavaScript

In this tutorial, we'll look at a couple of ways to replace all occurrences of a specified string using JavaScript. For all examples in this tutorial, we'll be using the following string:

const str = 'hello world! hello people! Hello hello!';

Using JavaScript replace() Function

The JavaScript replace() function takes two arguments:

  1. The string or regular expression to search for.
  2. The string to replace the matches found with.

Replacing First Match Only:

If we specify the first argument as string, the replace function only replaces the first occurrence of the string. Consider the example below:

str.replace('hello', 'hi'); // output: hi world! hello people! Hello hello!

The same can be re-written using a regular expression as the first argument, like so:

// method 1: regular expression literal notation — enclosed between slashes
str.replace(/hello/, 'hi');

// method 2: calling the constructor function of the RegExp object
str.replace(new RegExp('hello'), 'hi');

// Output: hi world! hello people! Hello hello!

While the literal notation can be a quick shorthand way of writing regular expressions, calling the constructor function of the RegExp object can be useful if you wish to use a variable.

If you wish to search for Regular Expressions' reserved characters (i.e. -/\^$*+?.()|[]{}), they will need to be escaped using a \ (backslash).

Replacing All Matches:

In order to replace all instances of the specified string, we need to use a regular expression as the first argument of the replace function with a "global" matching flag. Consider the example below:

// method 1: literal notation
str.replace(/hello/g, 'hi');

// method 2: RegExp object
str.replace(new RegExp('hello', 'g'), 'hi');

// Output: hi world! hi people! Hello hi!

The magic happens with the g flag of the regular expression which indicates a global search and replace.

Replacing All Matches With a Case-Insensitive Search:

In the previous example, you may have noticed that the regular expression search and replace is case-sensitive. We can make it case-insensitive by adding the i flag after the global flag, like so:

// method 1: literal notation
str.replace(/hello/gi, 'hi'); 

// method 2: RegExp object
str.replace(new RegExp('hello', 'gi'), 'hi');

// Output: hi world! hi people! hi hi!

Using the split() and join() JavaScript Functions

The JavaScript split function splits a string into an array based on a string (or regular expression), while the join function joins an array into a string. The join function takes as argument an optional string which can be used to join elements of array.

Replacing All Matches With a Case-Sensitive Search:

str.split('hello').join('hi'); // Output: hi world! hi people! Hello hi!

As you can see from the output of the example, this method does a case-sensitive search and replace.

Replacing All Matches With a Case-Insensitive Search:

// method 1: regular expression literal notation — enclosed between slashes
str.split(/hello/i).join('hi');

// method 2: calling the constructor function of the RegExp object
str.split(new RegExp('hello', 'i')).join('hi');

// Output: hi world! hi people! hi hi!

Doing a Custom Recursirve Search & Replace

As mentioned earlier in this article, when we supply string as the first argument of the replace function, it replaces only the first occurrence of the string. Using that information we can create a function that recursively goes through the entire string searching and replacing till all matches are replaced.

Replacing All Matches With a Case-Sensitive Search:

If you're using ES5+, you could use Object.defineProperty() like so:

Object.defineProperty(String.prototype, 'replaceAll', {
    // prevent it from being overwritten
    writable: false,
    // prevent it from being enumerated
    enumerable: false,
    // prevent it from being deleted
    configurable: false,

    value(searchStr, replaceStr) {
        const str = this;

        // no match exists in string?
        if (str.indexOf(searchStr) === -1) {
            // return string
            return str;
        }

        // replace and remove first match, and do another recursirve search/replace
        return str.replace(searchStr, replaceStr).replaceAll(searchStr, replaceStr);
    }
});

// usage:
str.replaceAll('hello', 'hi');

// output: hi world! hi people! Hello hi!

Unlike extending native objects by assignment (e.g. String.prototype.replaceAll = ...), Object.defineProperty() provides us with finer control over the property we add. For example, in the code above, it would add the new property replaceAll to String.prototype:

  1. in an immutable way;
  2. prevent it from being overwritten;
  3. prevent it from being deleted;
  4. prevent it from being enumerated (for example using for...in loop or Object.keys method).

Please also note that writable: false, enumerable: false and configurable: false are default values and can safely be ommited. They were added to show how these can be controlled via Object.defineProperty().

If you're not using ES5, then you may want to create an object or function instead. For example:

function replaceAll(str, searchStr, replaceStr) {
    // no match exists in string?
    if (str.indexOf(searchStr) === -1) {
        // return string
        return str;
    }

    // replace and remove first match, and do another recursirve search/replace
    return replaceAll(
        str.replace(searchStr, replaceStr),
        searchStr,
        replaceStr
    );
}

// usage:
replaceAll(str, 'hello', 'hi');

// output: hi world! hi people! Hello hi!

Replacing All Matches With a Case-Insensitive Search:

Since case-insensitive searches are easy with regular expressions, we can simply use regular expression with a gi flag. So, there is no real need to do a recursive search and replace in this instance.

// ES5+
Object.defineProperty(String.prototype, 'replaceAll', {
    writable: false,
    enumerable: false,
    configurable: false,
    value(searchStr, replaceStr) {
        const str = this;

        // escape regexp special characters in search string
        const pattern = searchStr.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

        return str.replace(new RegExp(pattern, 'gi'), replaceStr);
    }
});

// usage:
str.replaceAll('hello', 'hi');

// output: hi world! hi people! hi hi!
function replaceAll(str, searchStr, replaceStr) {
    // escape regexp special characters in search string
    const pattern = searchStr.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    
    return str.replace(new RegExp(pattern, 'gi'), replaceStr);
}

// usage:
replaceAll(str, 'hello', 'hi');

// output: hi world! hi people! hi hi!

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.