【问题标题】:splitting by first occurence of comma in javascript通过在 javascript 中第一次出现逗号来分割
【发布时间】:2018-07-25 13:39:16
【问题描述】:

我有一个表单的消息:

var message = 'hello.there, "how are you, doing"'

哪个需要被',' 的第一次出现分割,这样我就有两个对象,即'hello.there'(param 1) 和"how are you, doing(param 2)",这样param 2 应该是arguments(length=1) 的列表并且应该保留空格?

我尝试过类似的东西 var param2 = message.split(/,(.+)/)[1]

但这会导致 param2 成为字符串而不是参数列表。

【问题讨论】:

  • "should be a list of arguments..." 请澄清这部分,什么样的列表和论点?
  • 添加另一个示例假设我有一条消息,var mess = hello.there, "how are you, doing", 12 然后应该发生拆分,以便获得的参数 2 应该是一个列表,其中包含“你好吗,在做什么”和 12 个长度为 2 而不是3.

标签: javascript regex split


【解决方案1】:

只要找到第一个逗号,然后用那个逗号代替:

const pos = message.indexOf(",");
const param1 = message.substr(0, pos);
const param2 = message.substr(pos);

或者如果param2 应该是由逗号分隔的其他字符串的数组:

const [param1, ...param2] = message.split(",");

【讨论】:

    【解决方案2】:

    您必须找到第一个 , 的索引,在该索引处对字符串进行切片,然后将第二个切片除以 ,:

    var i = message.indexOf(',');    //find the index of the first ,
    var param1 = message.slice(0,i);    //param1 is the slice from 0 to i
    var param2 = message.slice(i+1).split(',');    //param2 is the slice from i+1 splitted at ,
    

    顺便说一句,还有一些其他方法可以通过第一次出现的标记来拆分数组。 This SO post 你可能会感兴趣。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多