How to remove a substring from a string in JavaScript

In this tutorial, let’s look at the different ways to remove a substring from a string in JavaScript. This substring could be a single character or more and can be present in any index.

We’re going to create a function that receives the string and the substring you want removed. We’ll be looking at methods that use both pre-defined and manual methods and functions. Let’s get to it then!

Remove substring from string using the ‘replace’ method

The simplest way of going about this is by using the ‘replace’ method. This method replaces the given substring with another string of your choice.

It only replaces the first occurrence of the string though, so if that’s all you need, you’re good to go.

Also, since we’re removing the given substring, and not replacing it with another substring, the second part of the arguments list should be an empty string, as shown below:

const removeSubstring = (str,substring) => {
    str = str.replace(substring,'');
    return str;
}

console.log(removeSubstring('Hello there!Yo!', 'Yo!')); // Hello there! 

As you can see, we wanted ‘Yo!’ removed from the string, and with the help of ‘replace’ we did just that.

Using regular expressions to remove the substring

You can also use regular expressions with the replace method, instead of just directly sending the string. Regular expressions are great in creating patterns.

For example, instead of just removing a substring, you can ask for every number and special character to be removed. You can make these conditions as simple or as complicated you want them to be.

It’s a vast topic though, so for now, let’s just look at how to make our search case insensitive. Before that, let’s look at how to replace the previous example with a regular expression.

Since we’re using a variable (substring) in our regular expression, we need to use the new RegExp syntax. The first argument of that syntax is the pattern we need to match, which is our substring in this case.

Then, we can use the replace method on the string, where the first argument is the regular expression and the second is the substring we want the first string replaced with (which is an empty string, to facilitate removal).

That’s it!

const removeSubstring = (str,substring) => {
    substring = new RegExp(substring);
    str = str.replace(substring,'');
    return str;
}

console.log(removeSubstring('Hello there!Yo!', 'Yo!')); // Hello there! 

Making the removal case insensitive

Continuing from the above example, you can make the removal case sensitive as well. Look at the below code snippet. As you can see, our string contains ‘Yo!’, but when we ask for ‘yo!’ to be removed, it doesn’t remove its capital counterpart.

This is because browsers associate different character codes with small and capital letters.

console.log(removeSubstring('Hello there!Yo!', 'yo!')); // Hello there!Yo! 

But regular expressions have a great way of making a string search case insensitive. Let’s use the same syntax as before to create our regular expression, only this time, let’s add the ‘i’ flag as the second argument.

substring = new RegExp(substring, 'i'); 

This way, when this regular expression is now used, the consequent search will now be case insensitive, as you can see below:

console.log(removeSubstring('Hello there!Yo!', 'yo!')); // Hello there! 

Removing all the occurrences of the substring from the string

So far, we’ve only looked at removing the first, or only occurrence of the substring from our string. What if there is more than one occurrence, and we want to remove them all?

There are 2 ways of doing that. Let’s look at them both.

Using the replaceAll method

One of the easiest ways to remove all the occurrences of a substring from a string is by using the replaceAll method. Look at the example below:

let str = 'Yo! Yo! Hello Yo! there! Yo!';

str = str.replaceAll('Yo!','');

console.log(str); //   Hello  there! - spaces are still present 

As you can see, all the occurrences of ‘Yo!’ was replaced with an empty string from our string, effectively removing it.

But there’s an issue with this method. This method does not work with regular expressions, and it is case sensitive. So, if you want to make your search case insensitive, you must go about things in a different way.

Using regular expressions

Regular expressions don’t just make a search case insensitive; they can also be used to replace/remove all the occurrences of a given substring.

You just need to use the ‘g’ flag, which refers to global (meaning: search for every occurrence globally in the given string), as shown below:

let str = 'Yo! Yo! Hello there! Yo!';

str = str.replace(/\s*Yo!\s*/g,'');

console.log(str); // Hello there! - no extra spaces 

You can also make the search/removal case insensitive by using the ‘i’ flag along with the ‘g’ flag, as shown below:

let str = 'Yo! Yo! Hello there! yo!';

str = str.replace(/\s*Yo!\s*/gi,''); 

Using the string slice and indexOf methods

The string ‘indexOf’ method can be used to find the index/position of a character, but did you know that you can use it for words or substrings as well? Yes, that’s correct!

When you look up the index of a substring using the ‘indexOf’ method, you’ll get back the position/index of the first character of the substring, which is exactly what we need.

We can use this starting index to slice off the substring from our string.

And for the ending index (position of the last character of the substring), finding the length of the substring and subtracting it by 1 will do the trick.

Look at the example below:

const removeSubstring = (str,substring) => {
    let index = str.indexOf(substring);
    str = str.slice(0,index) + str.slice(substring.length + index + 1);
    return str;
}

console.log(removeSubstring('Hello there!Yo!', 'Yo!')); // Hello there! 

As you can see, we sliced the string from the positions 0 to index, which would be the character right before the first character of our substring.

Then, we started slicing again from substring.length + index + 1, to get to the character right after the last character of our substring, which would conveniently leave out the substring from our string and retain the rest of the characters.

Using the substring method

You can use the ‘substring’ method in place of the ‘slice’ method to achieve the same result, as shown below:

str = str.substring(0,index) + str.substring(substring.length + index + 1); 

Using the split and join methods with loo

You can also use the ‘split’ method to get rid of the substring. As you know, this method can be used to convert a string to an array based on a split condition, which can be an empty string (every character would become a separate array element), single space (every word becomes an array element), and so on.

In our case, if we make the substring our split condition, then the text right before the substring and the text right after the substring would become 2 separate array elements.

Then, you can use the ‘join’ method with an empty string as the join condition to join back the array elements into a string, as shown below:

const removeSubstring = (str,substring) => {
    let index = str.indexOf(substring);
    str = str.split(substring).join('');
    return str;
}

console.log(removeSubstring('Hello there!Yo!', 'Yo!')); // Hello there! 

Using the string splice method with split and join

Instead, you can go about things the long way by splitting the array at every empty string, which would convert every character to an element.

Before the split though, you need to find the index of the substring using the indexOf method.

Then, after the split, use the ‘splice’ method and replace from the ‘index’ position, and replace ‘substring.length’ number of characters (the number of elements you want replaced).

Finally, give the replace condition as an empty string to remove the selected characters.

Join the array to get back the required string, as shown below:

const removeSubstring = (str,substring) => {
    let index = str.indexOf(substring);
    str = str.split('');
    str.splice(index,substring.length,'');
    str = str.join('');
    return str;
}

console.log(removeSubstring('Hello there!Yo!', 'Yo!')); // Hello there! 

That’s it! We’ve looked at the different ways to remove a substring from a string in JavaScript. We looked at many methods, including replace, replaceAll, indexOf, slice, split, join, and splice.

Leave a Comment