Remove or replace a substring in JavaScript
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:
|
1 2 3 4 5 6 7 8 9 10 |
let str = "Apples are red, Strawberries are red"; let substringToRemove = " are red"; // 1. Use the replace function to remove or replace the substring let newStr = str.replace(substringToRemove, ""); console.log(newStr); // Output: "Apples, Strawberries are red" // 2. Use the global flag (g) to replace all occurences newStr = str.replace(new RegExp(substringToRemove, 'g'), ""); console.log(newStr); // Output: "Apples, Strawberries" |
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:
|
1 2 3 4 5 6 7 8 |
let str = "Apples are red, Strawberries are red"; // The specific substring we want to remove let substringToRemove = " are red"; // Use the replaceAll function to remove or replace all occurences of the substring let newStr = str.replaceAll(substringToRemove, ""); console.log(newStr); // Output: "Apples, Strawberries" |
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:
|
1 2 3 4 5 6 7 8 |
let str = "Apples are red. Strawberries are red."; let substringToReplace = "red"; let replacementString = "delicious"; // Use the split function to split the string on the substring, followed by // the join function to join the array elements with a replacement string let newStr = str.split(substringToReplace).join(replacementString); console.log(newStr); // Output: "Apples are delicious. Strawberries are delicious." |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let str = "I love burgers and french fries."; // The specific substring we want to remove let substringToRemove = " and french fries"; // Find the start and end indices of the substring let startIndex = str.indexOf(substringToRemove); let endIndex = startIndex + substringToRemove.length; // Use the substring() or slice() function to extract the parts of the string // before and after the substring let before = str.substring(0, startIndex); // "I love burgers" let after = str.substring(endIndex); // "." // Use the concat function to combine the parts of the string let newStr = before.concat(after); console.log(newStr); // Output: "I love burgers." |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function removeSubstring(str, substring, replacement) { // initialize the result with an empty array let result = ""; // loop over each character in the string for (let i = 0; i < str.length; i++) { // check if the current character matches the first character of the substring and // the subsequent characters match the rest of the substring if (str[i] === substring[0] && str.slice(i, i + substring.length) === substring) { // Replace the target substring with another substring by adding it to the result result += replacement; // skip the string by incrementing i by target substring's length minus 1 i += substring.length - 1; } // else, add the current character to the result else { result += str[i]; } } return result; } let str = "Apples are red. Strawberries are red."; let substringToReplace = "red"; let replacementString = "delicious"; let newStr = removeSubstring(str, substringToReplace, replacementString); console.log(newStr); // Output: "Apples are delicious. Strawberries are delicious." |
That’s all about removing or replacing a substring in a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)