1


I have the following string:

var my_fruits = "Apples, Bananas, Mangos, Blackberries, Oranges";  

I want to remove "Mangos" (or any other fruit by giving a name) so that the new string would look like this:

"Apples, Bananas, Blackberries, Oranges".

How can i achieve this with/without JQuery?
Thanks in advance.

Regards

2 Answers 2

2

One approach uisng using an array, you can use $.grep() to filter an array you create from splitting based on the comma, like this:

var my_fruits = "Apples, Bananas, Mangos, Blackberries, Oranges";
var result = $.grep(my_fruits.split(', '), function(v) { return v != "Mangos"; }).join(', ');
alert(result);

You can test it here. Or in function form (since you want to pass in what to filter out):

function filterOut(my_str, t) { //string, term
  return $.grep(my_str.split(', '), function(v) { return v != t; }).join(', ');
}

You cant test that version here.

Sign up to request clarification or add additional context in comments.

Comments

1

You can perform a replace using a regular expression:

myFruits = myFruits.replace(/\bMangos(, |$)/gi, "");

The \b will match a word boundary.
The (, |$) will match either a or the end of the string.

3 Comments

This doesn't really suit the "or any other fruit by giving a name" part
to clarify: the fruit name (which will be removed) is defined from the beginning. how would it be, if I have the variable is "Bananas" instead of "Mangos"?
@Nick, Steilflug: new Regex("\\b" + name + "(, |$)", "gi")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.