i need split string looks this:
75,"first, result line third, or more" 77,"just 1 line"
what need object 2 fields, second field , array:
{ id: 75, lines: [ 'first, result', 'another line', 'third, or more' ] }, { id: 77, lines: [ 'just 1 line' ] }
my problem is, there linebreaks , commas. str.split(",");
doesn't work.
here's simple solution regular expression:
var arr, objs = [], r = /(\d+),\s*"([^\"]+)"/gm; while (arr=r.exec(str)){ objs.push({id:+arr[1], lines:arr[2].split('\n')}) }
see demonstration below:
var str = '75,"first, result\nanother line\nthird, or more"\n77,"just 1 line"'; var arr, objs = [], r = /(\d+),"(\s*[^\"]+)"/gm; while (arr=r.exec(str)){ objs.push({id:+arr[1], lines:arr[2].split('\n')}) } document.body.style.whitespace = 'pre'; document.body.textcontent = json.stringify(objs,null,'\t');
Comments
Post a Comment