JavaScript
Article

jQuery remove string from string

By Sam Deering

This is how you might go about using jQuery to remove string from string so to speak. The example below will hopefully clarify what I mean. It uses jQuery.grep() which is a really cool search function – It’s kind of a PHP substring equivalent… kind of anyways.

As always just copy, paste, run using Firebug to test out and experiment.

(function($) {
var myFruits = "Apples, Bananas, Mangos, Blackberries, Oranges";
myFruits = myFruits.replace(/bMangos(, |$)/gi, "");
 
var myFruits = "Apples, Bananas, Mangos, Blackberries, Oranges";
var result = $.grep(myFruits.split(', '), function(v) { return v != "Mangos"; }).join(', ');
console.log(result);
 
function filterOut(my_str, t) { //string, term
  return $.grep(my_str.split(', '), function(v) { return v != t; }).join(', ');
}
})(jQuery);

//output: Apples, Bananas, Blackberries, Oranges

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • http://www.reportersarchive.com/ in America

    very informetive …thanx alot

  • http://www.rafasirotheau.com.br Rafael

    great! theres just an error on the source:
    var result = $.grep(my_fruits.split(', '), function(v) { return v != "Mangos"; }).join(', ');

    should be:
    var result = $.grep(myFruits.split(', '), function(v) { return v != "Mangos"; }).join(', ');

    • jquery4u

      @Rafael – great spot mate, i’ve updated.

  • Scott

    you spelled fucntion wrong

    • http://jquery4u.com/ jQuery4u

      Cool

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.