How to Replace All Occurrences of a String in JavaScript

If you are working with JavaScript and need to replace all occurrences of a specific string within another string, you can follow a few different approaches. In this article, we will explore various methods to achieve this, providing code examples and explanations along the way.

Method 1: Using the replace() function with a regular expression

The replace() function is a built-in JavaScript method that allows you to replace a substring within a string with another string. By using a regular expression as the first parameter of the replace() function, you can replace all occurrences of a specific substring.

            
                let str = "Test abc test test abc test test test abc test test abc";
                let newStr = str.replace(/abc/g, "");
                console.log(newStr);
            
        

In the above example, we have used the regular expression /abc/g as the first parameter of the replace() function. The /g flag stands for "global", which means that all occurrences of the substring "abc" will be replaced.

Method 2: Splitting the string and joining it back together

Another approach to replace all occurrences of a string is to split the original string into an array of substrings using the split() function, and then join the array back together using the join() function.

            
                let str = "Test abc test test abc test test test abc test test abc";
                let arr = str.split("abc");
                let newStr = arr.join("");
                console.log(newStr);
            
        

In this example, we split the original string whenever the substring "abc" is encountered. This creates an array of substrings where "abc" is removed. Finally, we join the array back together using an empty string as the separator, resulting in a string where all occurrences of "abc" are replaced.

Method 3: Using a loop

If you prefer a more manual approach, you can use a loop to iterate through the string and replace each occurrence of the substring individually. Here's an example:

            
                let str = "Test abc test test abc test test test abc test test abc";
                let searchStr = "abc";
                let replaceStr = "";
                while (str.includes(searchStr)) {
                    str = str.replace(searchStr, replaceStr);
                }
                console.log(str);
            
        

In this code snippet, we start by setting the variables searchStr and replaceStr to the substring we want to replace and the string we want to replace it with, respectively. Then, we enter a while loop that continues as long as the original string contains the searchStr. Inside the loop, each occurrence of the searchStr is replaced with the replaceStr using the replace() function. The loop continues until all occurrences are replaced.

Method 4: Using a regular expression and a function callback

Lastly, you can also use a regular expression and a function callback with the replace() function to achieve the desired result. Here's an example:

            
                let str = "Test abc test test abc test test test abc test test abc";
                let newStr = str.replace(/abc/g, function(match) {
                    return "";
                });
                console.log(newStr);
            
        

In this example, we use the regular expression /abc/g with the replace() function, just like in Method 1. However, instead of passing a string as the second parameter, we pass a function callback. The function callback takes the matched substring as an argument and returns the replacement string. In this case, we simply return an empty string, effectively removing all occurrences of "abc".

Conclusion

Replacing all occurrences of a string within another string in JavaScript can be accomplished using various techniques. Whether you choose to use the replace() function with a regular expression, split and join the string, use a loop, or utilize a regular expression with a function callback, you have multiple options to choose from. Consider the specific requirements of your task and pick the method that suits your needs best.