Skip to content

Commit

Permalink
Escape double quotes according to RFC 4180 (#66)
Browse files Browse the repository at this point in the history
Fixes #65
  • Loading branch information
rgansevles committed Oct 27, 2023
1 parent 7f117d9 commit fd09d60
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
38 changes: 38 additions & 0 deletions lib/__specs__/main.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,44 @@ describe("ExportToCsv", () => {
);
});

it("should escape double quotes when quote is double quote", () => {
const options: ConfigOptions = {
quoteCharacter: '"',
filename: "Test Csv 2",
useBom: false,
showColumnHeaders: true,
useKeysAsHeaders: true,
};

const output = generateCsv(options)([
{
"escape-it": 24,
song: 'Mack "The Knife"',
},
]);

expect(output).toBe('"escape-it","song"\r\n24,"Mack ""The Knife"""\r\n');
});

it("should not escape double quotes when quote is not double quote", () => {
const options: ConfigOptions = {
quoteCharacter: "'",
filename: "Test Csv 2",
useBom: false,
showColumnHeaders: true,
useKeysAsHeaders: true,
};

const output = generateCsv(options)([
{
"escape-it": 24,
song: 'Mack "The Knife"',
},
]);

expect(output).toBe("'escape-it','song'\r\n24,'Mack \"The Knife\"'\r\n");
});

it("should properly quote headers", () => {
const options: ConfigOptions = {
filename: "Test Csv 2",
Expand Down
20 changes: 19 additions & 1 deletion lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,14 @@ export const formatData = (config: ConfigOptions, data: any): string => {
if (
config.quoteStrings ||
(config.fieldSeparator && data.indexOf(config.fieldSeparator) > -1) ||
(config.quoteCharacter && data.indexOf(config.quoteCharacter) > -1) ||
data.indexOf("\n") > -1 ||
data.indexOf("\r") > -1
) {
val = config.quoteCharacter + data + config.quoteCharacter;
val =
config.quoteCharacter +
escapeDoubleQuotes(data, config.quoteCharacter) +
config.quoteCharacter;
}
return val;
}
Expand All @@ -149,3 +153,17 @@ export const formatData = (config: ConfigOptions, data: any): string => {
}
return data;
};

/**
* If double-quotes are used to enclose fields, then a double-quote
* appearing inside a field must be escaped by preceding it with
* another double quote.
*
* See https://www.rfc-editor.org/rfc/rfc4180
*/
function escapeDoubleQuotes(data: string, quoteCharacter?: string): string {
if (quoteCharacter == '"' && data.indexOf('"') > -1) {
return data.replace(/"/g, '""');
}
return data;
}

0 comments on commit fd09d60

Please sign in to comment.