I want to parse the following strings
3693,"Toxic Avenger, The (1985)",Comedy|Horror
to
3693,
"Toxic Avenger, The (1985)",
Comedy|Horror.
similarly, the following
161944,The Last Brickmaker in America (2001),Drama
should be parsed to
161944
The Last Brickmaker in America (2001)
Drama
I can't do it by splitting by comma, since there is a comma within " , ".
The worked solution: LS05 suggested me to use "substring", so I did it and it worked perfect. here it is.
var pos1 = line.indexOf(',');
var line = line.substring(pos1+1);
pos1 = line.indexOf(',');
pos2 = line.lastIndexOf(',');
let movie_id = line.substring(0,pos1);
let movie_tag = line.substring(pos1+1,pos2);
let movie_timespan = line.substring(pos2+1);
Thanks to LS05 :)
You can use regex to parse your string which will exclude commas which are inside quotes
var str = '3693,"Toxic Avenger, The (1985)",Comedy|Horror';
console.log(str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g).join("\n"));
Demo (Refer to credits if you want to know how the above regex works)
As far as the code goes, I try to split your string ignoring the commas which are inside the string, and later we join the array items again using a new line character \n
Credits for Regex
You could use a CSV parser such as papa parse
or if you feel that a third party library is not needed you may take a look at this function
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With