Remove Value From Comma Separated Values String
Solution 1:
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(separator);
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(separator);
}
}
return list;
}
If the value you're looking for is found, it's removed, and a new comma delimited list returned. If it is not found, the old list is returned.
Thanks to Grant Wagner for pointing out my code mistake and enhancement!
John Resign (jQuery, Mozilla) has a neat article about JavaScript Array Remove which you might find useful.
Solution 2:
functionremoveValue(list, value) {
return list.replace(newRegExp(",?" + value + ",?"), function(match) {
var first_comma = match.charAt(0) === ',',
second_comma;
if (first_comma &&
(second_comma = match.charAt(match.length - 1) === ',')) {
return',';
}
return'';
});
};
alert(removeValue('1,2,3', '1')); // 2,3alert(removeValue('1,2,3', '2')); // 1,3alert(removeValue('1,2,3', '3')); // 1,2
Solution 3:
values is now an array. So instead of doing the traversing yourself.
Do:
var index = values.indexOf(value);
if(index >= 0) {
values.splice(index, 1);
}
removing a single object from a given index.
hope this helps
Solution 4:
Here are 2 possible solutions:
functionremoveValue(list, value) {
return list.replace(newRegExp(value + ',?'), '')
}
functionremoveValue(list, value) {
list = list.split(',');
list.splice(list.indexOf(value), 1);
return list.join(',');
}
removeValue('1,2,3', '2'); // "1,3"
Note that this will only remove first occurrence of a value.
Also note that Array.prototype.indexOf
is not part of ECMAScript ed. 3 (it was introduced in JavaScript 1.6 - implemented in all modern implementations except JScript one - and is now codified in ES5).
Solution 5:
// Note that if the source is not a proper CSV string, the function will return a blank string ("").functionremoveCsvVal(var source, var toRemove) //source is a string of comma-seperated values,
{ //toRemove is the CSV to remove all instances ofvar sourceArr = source.split(","); //Split the CSV's by commasvar toReturn = ""; //Declare the new string we're going to createfor (var i = 0; i < sourceArr.length; i++) //Check all of the elements in the array
{
if (sourceArr[i] != toRemove) //If the item is not equal
toReturn += sourceArr[i] + ","; //add it to the return string
}
return toReturn.substr(0, toReturn.length - 1); //remove trailing comma
}
To apply it too your var values:
var values = removeVsvVal(selectedvalues, "2");
Post a Comment for "Remove Value From Comma Separated Values String"