[英]splitting by first occurence of comma in javascript
I have a message of the form: 我收到以下形式的消息:
var message = 'hello.there, "how are you, doing"
' var message = 'hello.there, "how are you, doing"
”
Which needs to be split by the first occurrence of ','
such that I have two objects namely 'hello.there'(param 1)
and "how are you, doing(param 2)"
such that param 2
should be a list of arguments(length=1)
and spaces should be preserved? 需要用第一次出现的
','
将其拆分','
这样我就有两个对象,即'hello.there'(param 1)
和"how are you, doing(param 2)"
,因此param 2
应该是arguments(length=1)
和空格应该保留吗?
I have tried something like var param2 = message.split(/,(.+)/)[1]
我尝试过类似
var param2 = message.split(/,(.+)/)[1]
but that would result in param2 being a string instead of list of arguments. 但这将导致param2是字符串而不是参数列表。
Just find the first comma, then substr by that: 只需找到第一个逗号,然后按该即可:
const pos = message.indexOf(",");
const param1 = message.substr(0, pos);
const param2 = message.substr(pos);
Or if param2
should be an array of the other strings seperated by a comma: 或者,如果
param2
应该是用逗号分隔的其他字符串的数组:
const [param1, ...param2] = message.split(",");
You would have to find the index of the first ,
, slice the string at that index, and then split the second slice by ,
: 你必须找到第一个指数
,
即指数在切片的字符串,然后通过分割第二片,
:
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 ,
By the way, there are some other methods as well for splitting an array by first occurrence of a token. 顺便说一下,还有其他一些方法可以通过首次出现令牌来拆分数组。 This SO post might interest you.
这样的帖子可能会让您感兴趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.