remove value from comma separated values string

前端 未结 9 1846
不知归路
不知归路 2020-12-30 05:27

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

9条回答
  •  感动是毒
    2020-12-30 06:18

    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.

提交回复
热议问题