How to deal with Commas in CSV using Javascript

Viewed 19157

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.

5 Answers

This is how I have achieved the reported functionality.

In brief: Requirement was to fetch the comma-separated string as it is in the CSV Export.

Assuming that we have a comma-separated string which needs to be exported in the CSV as it is.

For example String value which comes from the data source as:

'StackOverflow', 'Awesome! work by StackOverflow team, cheers to them.'

Solution:

['stackoverflow', 'Awesome! work by stackoverflow team, cheers to them.'].map(string => string === null ? '' : `\"${string}\"`);

Explanation: So if we quote the comma-separated values and try exporting than the CSV will not consider the comma(,) as a field separator and due to which in CSV export it won't split into multiple columns with respect to numbers of available commas. And the content will appear in the same column.

Ref wiki link: Comma-separated_values

Hope this helps. Cheers!!

Use double-quotes enclosed string and escape double-quotes in string:

csvData.push( "\\"" + strData.replace( /\\"/g , "\\"\\"" ) + "\\"" )
Related