5

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 :)

arslan
  • 2,034
  • 7
  • 34
  • 61

2 Answers2

7

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

Community
  • 1
  • 1
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • This removes `,` at the end of line. `join(",\n")` may help – RaR Feb 22 '17 at 09:37
  • it has a problem. can't parse this string '161944,The Last Brickmaker in America (2001),Drama'. removed the strings if there are no " ". – arslan Feb 22 '17 at 09:55
  • I added one more example. could you check it out please! – arslan Feb 22 '17 at 09:57
  • @alim You need to tweak your regex - https://jsfiddle.net/cc38s1a6/1/ example, but you need to tweak that so it works with any types of quotes – Mr. Alien Feb 22 '17 at 10:11
  • @alim Try this `console.log(str.match(/(["'].*?["']|[^",\s]+)(?=\s*,|\s*$)/g).join("\n"));` (not 100% sure though if it might break something else), this will accept single and double quoted strings – Mr. Alien Feb 22 '17 at 12:36
2

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.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928