user448038
user448038

Reputation:

Jquery - Remove Particular String from String and return new string


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

Upvotes: 1

Views: 4374

Answers (2)

Nick Craver
Nick Craver

Reputation: 630429

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.

Upvotes: 2

SLaks
SLaks

Reputation: 887449

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.

Upvotes: 1

Related Questions