I'm working with a CSV string that contains double quotes (") around a person's first and last name for the purpose of having the full name in a single cell. The double-quoted value also contains a comma because the name is in "last name, first name" order. Ex: "Smith, Matt".
I'm creating a CSV file from this string using the following JavaScript:
//shortened example of the CSV string
let csv = [
["Smith, Matt", 'Developer'],
];
var blob = new Blob([csv], { type: 'text/csv' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
let link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", "test.csv");
link.setAttribute("target", '_self');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
The CSV file that's created from this doesn't enforce the double quote with the comma. The double quote is getting rendered as an entity character in the CSV file and the comma is enforcing the separation of the values into separate cells:
| Name | Role | |
|---|---|---|
"Matt |
Smith" |
Developer |
I don't have the option of changing the "last name, first name" order in the string, so the comma is going to be required in the name value. Is there a way to download the CSV file and have the double quote enforce the rule that even if they contain a comma in the value, the full quoted value should be in the same cell?
The easiest approach is changing the delimiter to one which don`t use in your entities. For example, you can use comma sign.
let rawCsv = [
["Smith, Matt", 'Developer'],
];
let csv = rawCsv.map(x=>{
return x.join(';');
})
// saving file