This post will discuss how to remove or replace a substring in a string in JavaScript.

There are several ways to remove or replace a substring in a string in JavaScript. A substring is a part of a string that can be identified by a start and end index, or by a matching pattern. To remove or replace a substring in a string in JavaScript, we need to use some function or function that can find and modify the substring in the string.

1. Using replace() or replaceAll() function

The replace() function takes two arguments, the substring to be replaced and the new string to replace it with. It searches for a specified substring within a string and replaces it with a new substring. By default, it replaces only the first occurrence of the specified substring, but we can use a regular expression with the global flag (g) to replace all occurrences. For instance:

Download  Run Code

 
Alternatively we can use the replaceAll() function to replace all occurrence of the specified substring in the string. It is similar to the replace() function, but it doesn’t need a regular expression to replace all occurrences of the substring. It is a newer feature and may not be supported by older browsers. For instance:

Download  Run Code

2. Using split() and join() functions

These functions allow us to split a string into an array of substrings based on a separator, and then join the array elements back into a string with a different separator. We can use these functions to remove a substring from a string by splitting the string on the substring and joining the array elements with an empty string (or with replacement string if needed). For instance:

Download  Run Code

3. Using substring() and concat() functions

These functions allow us to extract a portion of a string based on specified start and end indices, and then combine two or more strings. We can use these functions to remove or replace a substring from a string by finding the indices of the substring, extracting the parts of the string before and after the substring, and then concatenating them together (or with replacement string if needed). For instance:

Download  Run Code

4. Using a loop

Another option to remove or replace a substring in a string by using a for loop, that iterates over each character in the string and checks if it matches the target substring. If it does, it skips it or replaces it with another substring and adds it to an array. If it does not, it adds it to the array without changing it. Then, it joins the array into a new string. Here’s an example of how we can achieve this:

Download  Run Code

That’s all about removing or replacing a substring in a string in JavaScript.