Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with Commas in CSV using Javascript

I am having some data which is facing issue while exporting to csv if the data contains "," with in it.

Hereis the code:

  CSVData.push('"' + item.OrgId+ '","' + item.Name + '","' + item.OrgDescriptionString + '","' + itam.OrgDetailsString + '","' + item.Active+ '"');

if orgDetaisl string contains "," with in it, the data is getting overlapped and moving to next column.

How to escape "," .I tried using double quotes """ but not sure how can i achieve.

CSVData.push('"' + item.OrgId+ '","' + item.Name + '","\""' + item.OrgDescriptionString + '"\"","\""' + item.OrgDetailsString + ' \"","' + item.Active+ '"');

Please correct the string and help me to escape "," with in the data.

like image 402
AMDI Avatar asked May 22 '17 11:05

AMDI


2 Answers

The proper way to escape separators inside fields is to enclose the fields in double quotes:

Id,Description
123,"Monitor, Samsung"

But then quotes inside the field have to be escaped with another quote:

Id,Description
123,"Monitor 24"", Samsung"

Of course, a different delimiter like ; could be used, but then you'd still have to check if those appear in the data.

like image 58
Danny_ds Avatar answered Sep 28 '22 12:09

Danny_ds


I tried to with the below code and it worked for me

item.OrgDescriptionString.replace(/\"/g, "\"\"");

I tried to escape single quotes in the string and it worked.

like image 32
AMDI Avatar answered Sep 28 '22 11:09

AMDI