Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  167] [ 6]  / answers: 1 / hits: 49228  / 15 Years ago, thu, august 20, 2009, 12:00:00

I have a csv string like this 1,2,3 and want to be able to remove a desired value from it.



For example if I want to remove the value: 2, the output string should be the following:



1,3



I'm using the following code but seems to be ineffective.



var values = selectedvalues.split(,);
if (values.length > 0) {
for (var i = 0; i < values.length; i++) {
if (values[i] == value) {
index = i;
break;
}
}
if (index != -1) {
selectedvalues = selectedvalues.substring(0, index + 1) + selectedvalues.substring(index + 3);
}
}
else {
selectedvalues = ;
}

More From » csv

 Answers
58
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.


[#98866] Monday, August 17, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
diamondlauryna

Total Points: 386
Total Questions: 93
Total Answers: 103

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
;