开发者

How to split a String for every 3 occurrences of a character?

开发者 https://www.devze.com 2023-01-27 16:38 出处:网络
I\'m struggling to figure out how to split a text for every 3 occurrences of the \"|\" character. Here is my input:

I'm struggling to figure out how to split a text for every 3 occurrences of the "|" character. Here is my input:

123 | name1 | description 开发者_运维知识库| $ 2.980,00 | 234 | name2 | description | $ 2.980,00 | 345 | name3 | description | $ 2.980,00

This would be my desired output:

var array[0] = "123 | name1 | description | $ 2.980,00"
var array[1] = "234 | name2 | description | $ 2.980,00"
...


I would do it this way (as Keng mentioned, it's called tokenizing):

var myarray=text.split("|");
var json = new Array();
for (var i=0; i+3<myarray.length; i+=4) {
 json.push({id: myarray[i], name: myarray[i+1],
         desc: myarray[i+2], price: myarray[i+3]});
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号