在JavaScript中,每第二个逗号后拆分字符串

huangapple go评论70阅读模式
英文:

String split in javascript after each second comma

问题

I want to split the string at every second comma. Here's the desired output:

Array[1] = 16First,Second,
Array[2] = 18Third,Fourth,
Array[3] = 25Fifth,Sixth,
Array[4] = 38Seven,Eight

英文:

I am having this string:

16First,Second,18Third,Fourth,25Fifth,Sixth,38Seven,Eight

I want to split the string in a way that it will produce and array containing each element after the second comma, basically

16First,Second,(split here)18Third,Fourth,(split here)25Fifth,Sixth,(split here)38Seven,Eight

So the final output would be an array like this:

Array[1] = 16First,Second,
Array[2] = 18Third,Fourth,
Array[3] = 25Fifth,Sixth,
Array[4] = 38Seven,Eight

And so on no matter how long the string is. I am confused because it needs to split on each 2nd comma and there isn't ( or at least I haven't find any guide/solution about it ).

答案1

得分: 3

我会在这里使用正则表达式匹配所有的方法,使用 match() 来帮助:

var input = "16First,Second,18Third,Fourth,25Fifth,Sixth,38Seven,Eight";
var matches = input.match(/[^,]+,[^,]+/g);
console.log(matches);

如果您需要进一步的帮助,请告诉我。

英文:

I would use a regex match all approach here with the help of match():

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var input = &quot;16First,Second,18Third,Fourth,25Fifth,Sixth,38Seven,Eight&quot;;
var matches = input.match(/[^,]+,[^,]+/g);
console.log(matches);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月17日 10:08:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定