jQuery从逗号分隔列表中删除值

时间:2011-01-03 20:14:08

标签: javascript jquery

给出如下输入:

<input type="test" value="3,4,9" />

删除9,4或3之类的值的最佳方法是什么,没有逗号问题,我不希望这样结束:

value="3,4,"
value="3,,9"
value=",4,9"

有没有一种干净的方法可以在JavaScript / jQuery中完成这项工作?

9 个答案:

答案 0 :(得分:6)

您可以将值拆分为数组,然后过滤掉您不想要的值。

$("input[type='test']").val().split(",") // ["3","4","9"]
.filter(function(v){return !isNaN(parseInt(v))})    // filter out anything which is not 0 or more

这是一个不太简洁的版本,可以过滤掉任何非数字

的内容
var array = $("input[type='test']").val().split(",");

// If you are dealing with numeric values then you will want
// to cast the string as a number
var numbers  = array.map(function(v){ return parseInt(v)});

// Remove anything which is not a number
var filtered = numbers.filter(function(v){ return !isNaN(v)});

// If you want to rejoin your values
var joined = filtered.join(",");

最后更改输入值

$("input[type='test']").val(joined);

答案 1 :(得分:2)

类似于PHP内爆/爆炸功能

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

var explode = value.split(',');
explode.remove(1);
var implode = explode.join(',');

文档:
fce: Split
fce: Join
fce: Array.remove

答案 2 :(得分:1)

不需要jQuery:P

<script type="text/javascript">

    //var subject = '3,4,9';
    //var subject = '3,,9';
    var subject = ',,4,9';

    var clean = Array();
    var i = 0;

    subject = subject.split(',');

    for (var a in subject)
    {
        if(subject[a].length)
        {
            clean[i] = subject[a];
            i++;
        }
    }

    document.write(clean.join(','));

</script>

答案 3 :(得分:1)

您也可以使用纯JavaScript。假设你只想起飞“4”:

value = value.replace(/4,?/, '')

或“3”和“9”:

value = value.replace(/([39],?)+/, '')

答案 4 :(得分:0)

我认为此功能适用于您尝试执行的操作:http://www.w3schools.com/jsref/jsref_split.asp

string.split(separator, limit)

答案 5 :(得分:0)

使用

array = string.split(separator);

将字符串分解为数组。然后在操作后使用它加入。

string = array.join(separator);

答案 6 :(得分:0)

var ary = value.split(',');
ary.splice(indexOfItemToRemove,1)
var result = ary.join(',');

答案 7 :(得分:0)

这在另一篇文章中讨论:

remove value from comma separated values string

var removeValue = function(list, value, separator) {
   separator = separator || ",";
   var values = list.split(",");
   for(var i = 0 ; i < values.length ; i++) {
      if(values[i] == value) {
         values.splice(i, 1);
         return values.join(",");
      }
   }
   return list;
}

答案 8 :(得分:0)

您可以使用此功能:

function removeComma(x) {
    var str = '';
    var subs = '';

    for(i=1; i<=x.length; i++) {
        subs = x.substring(i-1, i).trim();

        if(subs !== ',') {
            str = str+subs;
        }
    }

    return str;
}