Categories
JavaScript

JavaScript string replace

In our latest JavaScript article, we covered 2 easy ways to check if a JavaScript string contains a substring. In this article, we are going to cover the JavaScript string replace method.

According to MDN: The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If a pattern is a string, only the first occurrence will be replaced.

So the replace() method returns a new string with some or all matches of a pattern replaced, depending on whether we used RegEx or another string. If we used RegEx then every occurrence will be replaced. But, if we used another string only the first occurrence will be replaced.

JavaScript string replace syntax

JavaScript string replace method has a simple syntax and accepts two parameters:

  • substr– the string, or the RegEx that will be replaced by newSubstr
  • newSubstr – the string that will replace substr

We can also use two additional parameters:

  • RegEx – object or literal. We use it to match desired substr or in replacer function.
  • Replacer function – instead of passing newSubstr we can pass a replacer function that will manipulate matched data and return new string.

Let’s create an example of JavaScript string replace method syntax.

string.replace(substr, newSubstr);

replace() method using string

After we’ve seen the syntax of the JavaScript string replace method, now, we are going to see it in action, using substr.

let str = "This is a simple string. Simple!"

console.log(str.replace('simple', 'complex'));

// Result:
// This is a complex string. Simple!

As we can see from the example above, only the first occurrence of the substring ‘simple’ is replaced. This is because we have used string as substr and not RegEx.

JavaScript string replace with RegEx

In order to remove every occurrence of substr we need to use RegEx. Either object or literal. Also, RegEx is better than the usual substr because it gives us more power and is more precise.

let str = "This is a simple string. Simple!";
let re = /simple/gi; //Global flag - g and case insesitive - i

console.log(str.replace(re, 'complex'));

// Result:
// This is a complex string. complex!

If we want to match every occurrence of substr, using RegEx, we have to use a global flag g, as we did in re variable. The flag i is case-insensitive, which means that it will find occurrences that are not exactly the same as substr. This is what we did. Even though the second substring Complex was capitalized, it was “found” by RegEx because of the i flag. For more info on RegEx, we can visit MDN.

Replacer function

Probably the hardest concept to understand about the JavaScript string replace method is a Replacer function. Instead of passing a substitute string, newSubstr, we can pass a function that will return a new string.

let result = str.replace(substr / regexp, replacerFunction);

So, as the first parameter, we pass either substr or RegEx, and as the second parameter, instead of newSubstr, we pass Replacer function, as we can see from the code snippet above.

Now let’s create a real-world example of how this will work.

let str = "Using JavaScript we can achieve and create almost anything!"
let re = /javascript|achieve|create|anything/gi;

let result = str.replace(re, (match) => { 
    return match.toUpperCase();
});

console.log(result);

// Result:
// Using JAVASCRIPT we can ACHIEVE and CREATE almost ANYTHING!

Let’s take a closer look at the example above. So we had a string and we created certain RegEx criteria that should be met. After that, we passed the criteria to the replace() method and we added the Replacer function as the second parameter. Then we passed match to the Replacer function. match is being processed by function and returned.

If we use g flag in our RegEx criteria, for every match JavaScript will run the Replacer function. For more in-depth info on the Replacer function we can visit MDN.

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like WordPress post loop – part 1.