代码之家  ›  专栏  ›  技术社区  ›  user244394

javascripts正则表达式

  •  0
  • user244394  · 技术社区  · 14 年前

    我有这根绳子1,2,3,4,5

    假设我去掉1,它变成,2,3,4,5或1,2,4,5

    如何从列表中删除“1”或任何数字,并替换这些多余的逗号,还要记住最后一个数字“5”没有逗号。

    我可以使用字符串替换javascript函数,我更关心最后一个数字

    它应该显示为1,2,3,4

    4 回复  |  直到 14 年前
        1
  •  4
  •   kennytm    14 年前
    theString.replace(/«the number»,?|,«the number»$/, '')
    
    >>> "1,2,3,4,5".replace(/1,?|,1$/, '')
    "2,3,4,5"
    >>> "1,2,3,4,5".replace(/2,?|,2$/, '')
    "1,3,4,5"
    >>> "1,2,3,4,5".replace(/5,?|,5$/, '')
    "1,2,3,4"
    

    或者将字符串作为数组,使用

    theString.split(/,/).filter(function(x){return x!="«the number»";}).join(",")
    
    >>> "1,2,3,4,5".split(/,/).filter(function(x){return x!="1";}).join(",")
    "2,3,4,5"
    >>> "1,2,3,4,5".split(/,/).filter(function(x){return x!="2";}).join(",")
    "1,3,4,5"
    >>> "1,2,3,4,5".split(/,/).filter(function(x){return x!="5";}).join(",")
    "1,2,3,4"
    
        2
  •  2
  •   Jason McCreary    14 年前

    split() 将字符串放入逗号上的数组中,然后根据需要删除元素。你可以用 join() 把它们串起来。

        3
  •  1
  •   jball    14 年前
    function removeValue(value, commaDelimitedString)
    {
        var items = commaDelimitedString.split(/,/);
        var idx = items.indexOf(value);
        if(idx!=-1) { items.splice(idx, 1); }
        return items.join(",");
    }
    
        4
  •  0
  •   Sairam    14 年前