To remove a string from an array in JavaScript, the easiest way is to use the JavaScript Array filter() method.

Below shows an example of how you could remove the string “hello” from an array of strings with filter() method.

var array_of_strings = ["hello","goodbye","Hello","hey","hi"];

var filtered_array = array_of_strings.filter(x => x != "hello");

console.log(filtered_array);

// Output:
['goodbye', 'Hello', 'hey', 'hi']

If you want to be more explicit with the callback function to filter(), you can do the following.

var array_of_strings = ["hello","goodbye","Hello","hey","hi"];

var filtered_array = array_of_strings.filter(function(x) {
  return x != "hello";
});

console.log(filtered_array);

// Output:
['goodbye', 'Hello', 'hey', 'hi']

When working with arrays in JavaScript, it can be valuable to be able to easily filter and remove unwanted values from your array.

One such situation is where you may want to remove all instances of a string from an array.

We can easily remove a string from an array in JavaScript using the JavaScript array filter() method.

To use filter(), you need to pass a callback function which will provide logic to identify the value or values you want to remove.

Below are a few more examples of how you can use the filter() method to filter out a string from arrays in JavaScript.

If you have an array of strings, you can easily filter out any strings with filter().

var array_of_strings = ["This","toRemove","is","an","array","toRemove","with","strings","toRemove","we","want","to","remove","."];

var filtered_array = array_of_strings.filter(x => x != "toRemove");

console.log(filtered_array);

// Output:
['This', 'is', 'an', 'array', 'with', 'strings', 'we', 'want', 'to', 'remove', '.']

Using a For Loop to Remove a String From Array in JavaScript

We can also remove a string from an array using a for loop with an if conditional statement. Here is a simple function we will create to remove a string from an array.

function removeString(str,arr){
  var new_array = [];
  for (var i=0; i

Let's see this code in action with our simple example from above.

function removeString(str,arr){
  var new_array = [];
  for (var i=0; i

Hopefully this article has been useful for you to learn how to remove a string from array in JavaScript.

Categorized in:

JavaScript,

Last Update: March 11, 2024