英文:
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 = "16First,Second,18Third,Fourth,25Fifth,Sixth,38Seven,Eight";
var matches = input.match(/[^,]+,[^,]+/g);
console.log(matches);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论