JavaScript String replace() Method

How to use the replace() method to replace all or some occurences of a string.

Syntax:

const result = str.replace(regExpression|subString, newSubString|function)

Parameters:

  • regExpression: A RegExp object or literal. The match(es) are replaced with newSubStrting or what the specified function returns.
  • subString: A string that it will get replaced by the newSubString or what the specified function returns. Note that only the first occurrence will get replaced.
  • newSubString: A string that will be used as a replacement for the matched strings specified by the regExpression or subString.
  • function: A function that returns a new string to be used as a replacement for the matched strings specified by the regExpression or subString.

Result:

A new string with some or all the matched strings replaced.


Using Regular Expressions

RegExp Match first occurence

How to use regular expressions to match and replace a string. The regular expression is defined in the replace() method as the first parameter and is the exact match of what we are trying to replace and it will return only the first match that it finds.

const initialString = `Hello world, check out the coder's tutorial`;
const result = initialString.replace(/coder's/, `PicoCoder's`); 
// result = 'Hello world, check out the PicoCoder's tutorial';

RegExp match all occurences using a string literal

In order to match all the strings the regular expression must include the g modifier which stands for global. Take a look at the example below:

const initialString = `Hello world, check out the coder's tutorial coder's`;
const result = initialString.replace(/coder's/g, `PicoCoder's`); 
// result = 'Hello world, check out the PicoCoder's tutorial PicoCoder's';

Therefore, the results pretty much rely on how will use the regular expressions and what that regular expression will match. You can check out this website to see what your regular expression is matching.

RegExp match all occurences using a constructor

If you would like to use the constructor to create a regular expression you can do as below:

  const initialString = `Hello world, check out the coder's tutorial coder's`;
  const regularExpression = new RegExp(`coder's`, 'g');
  const result = initialString.replace(regularExpression, `PicoCoder's`);
  // result = 'Hello world, check out the PicoCoder's tutorial PicoCoder's';

Which has the same results as when we pass the regExp as a string in the replace() function. There are a lot more to learn about regular expressions but it falls outside of the scope of this tutorial. However, if you want to learn more you can look here.


Using Split and Join

A different solution would be use split and joins. By using split you can split a string into an array of strings. For example, let's say we have a string of name and surname like this John Snow. If we use split and we split by the space character then we will end up with ['John', 'Snow'].

Let's see a different example how to combine split with join to achieve the results we want.

  const initialString = `Hello world, check out the coder's tutorial coder's`;
  const result = initialString.split(`coder's`).join(`PicoCoder's`);
  // result = 'Hello world, check out the PicoCoder's tutorial PicoCoder's';

So we used split to split the initialString into an array of strings excluding the string that we used for split and then we join the array of strings again.

Note: This approach is not as performant as using regular expressions.


JavaScript Replace All Comas in a String

How we can replace all comas in a string using the 2 methods described earlier:

Using regular expressions as before we can do:

const initialString = `Hello world, check out, the coder's tutorial coder's`;
const result = initialString.replace(/,/g, ' '); 
// result = 'Hello world check out the coder's tutorial coder's';

Using split and join to remove all comas in as string:

const initialString = `Hello world, check out, the coder's tutorial coder's`;
const result = initialString.split(',').join('');
// result = 'Hello world check out the coder's tutorial coder's';

As you can see this will remove the comas in the initial string.


Replace vs Split and Join Benchmark

Using replace we can achieve  218.1% increase in performance when trying to find and replace all occurrences of a string in JavaScript.

Here are my results:

Running the benchmark for replace vs split and join
const fs = require('fs');

const timer = () => {
    const start = new Date();
    return {
        stop: function () {
            const end = new Date();
            return end.getTime() - start.getTime();
        }
    }
};

const benchmarkReplace = () => {
    fs.readFile('./loremIpsum', 'utf8', (err, data) => {
        const t = timer('Using the replace method');
        data.replace(/lorem/gmi, `lor`);
        console.log(`Replace method: ${t.stop()}`);
    });
}

const benchmarkSplit = () => {
    fs.readFile('./loremIpsum', 'utf8', (err, data) => {
        const t = timer('Using split and join');
        data.split(/lorem/gmi).join(`lor`);
        console.log(`Split and Join time: ${t.stop()}`);
    });
}

// for (i = 1; i <= 10; i += 1) {
//     benchmarkReplace();
// }

for (i = 1; i <= 10; i += 1) {
    benchmarkSplit();
}

You can find the code in my github.


If you liked the tutorial, please consider subscribing to my blog. That way I get to know that my work is valuable to you and also notify you for future tutorials. Stay tuned!