removing value of imploded vars with javascript
i have this javascript var:
var mylist = '1,5,3,7,9,8,44,6';
I need to remove the 9, so that the final value is: 1,5,3,7,8,44,6
I usually do this server side开发者_开发技巧 with php (easy way). How can achieve this with javascript? A solution using jQuery would be even better.
considerations: it should work also if var is '99,9,96' or '9' or '99,9' or '9,98' ...etc.
my_list = my_list.split(',').filter(function(e) { return e != 9}).join(',');
Later edit: to support array.filter in IE:
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
My suggestion:
var mylist = '1,5,3,7,9,8,44,6';
mylist = mylist.split(',').filter(function(elem, i) {
return elem !== '9';
}).join(',');
console.log(mylist); // = 1,5,3,7,8,44,6
Ref.: .filter()
filter():
Creates a new array with all elements that pass the test implemented by the provided function.
精彩评论