从逗号分隔值字符串中删除值 [英] remove value from comma separated values string

查看:155
本文介绍了从逗号分隔值字符串中删除值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv字符串,像这样1,2,3,并希望能够从中删除所需的值。

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

例如,如果我想要删除值:2,输出字符串应为以下内容:

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


推荐答案

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)有一篇关于您可能会发现有用的JavaScript数组删除

John Resign (jQuery, Mozilla) has a neat article about JavaScript Array Remove which you might find useful.

这篇关于从逗号分隔值字符串中删除值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆