【问题标题】:How do I split a string with multiple separators acting only as one in javascript?如何拆分具有多个分隔符的字符串,仅在 javascript 中充当一个分隔符?
【发布时间】:2012-11-27 00:46:55
【问题描述】:

我想使用“空格和逗号”(“,”)作为分隔符将字符串拆分为数组。通过查看一些类似的问题,我想出了如何使它们作为一个分隔符工作。但是我希望他们只作为一个工作。所以我不希望数组只用逗号或空格分隔。 所以我希望字符串 "txt1, txt2,txt3 txt4, t x t 5" 成为数组 txt1, "txt2,txt3 txt4", "t x t 5" 这是我当前不这样做的代码:

var array = string.split(/(?:,| )+/)

这里是 jsFiddle 的链接:http://jsfiddle.net/MSQxk/

【问题讨论】:

    标签: javascript jquery arrays split


    【解决方案1】:

    只要做:var array = string.split(", ");

    【讨论】:

      【解决方案2】:

      你可以用这个

      var array = string.split(/,\s*/);
      //=> ["txt1", "txt2", "txt3", "txt4", "t x t 5"]
      

      这将补偿诸如

      之类的字符串
      // comma separated
      foo,bar
      
      // comma and optional space
      foo,bar, hello
      

      如果您想补偿逗号两边的可选空格,您可以使用:

      // "foo,bar, hello , world".split(/\s*,\s*);
      // => ['foo', 'bar', 'hello', 'world']
      

      【讨论】:

        猜你喜欢
        • 2010-10-13
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        • 1970-01-01
        • 2012-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多