开发者

Jquery - Remove Particular String from String and return new string

开发者 https://www.devze.com 2023-01-25 23:20 出处:网络
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

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, Ban开发者_运维问答anas, Blackberries, Oranges".

How can i achieve this with/without JQuery?

Thanks in advance.

Regards


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消