remove value from comma separated values string

csv, javascript

Solution

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.

Problem

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 = ""; } ```

Original source