Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js, how to parse strings like this?

Tags:

javascript

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

like image 264
arslan Avatar asked Feb 06 '23 01:02

arslan


2 Answers

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

like image 123
Mr. Alien Avatar answered Feb 07 '23 17:02

Mr. Alien


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.

like image 33
Darin Dimitrov Avatar answered Feb 07 '23 18:02

Darin Dimitrov