Regular Expressions

Replace all occurrences found on a string using Regular Expressions

Published on July 18th, 2020

Let's say you have the following string and you must replace all occurrences of "Hello" with "Bye":

var str = "Hello Hello Hello World";

You may think of using the .replace() method to solve this problem:

var newStr = str.replace("Hello", "Bye")

But unfortunately, it only replaces the first occurrence in the string:

console.log(newStr); // returns "Bye Hello Hello World" as the output.

Using the power of Regular Expressions, you can replace all occurrences in one go:

function replaceAll(str, search, replace){
    var re = new RegExp(search, "g");
    return str.replace(re, replace);

Now, when you execute the following, you'll get a string that replaced all occurrences:

var newStr = replaceAll(str, "Hello", "Bye");
console.log(newStr); // returns "Bye Bye Bye World" as the output.

Until next time, then!