Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape double quotes according to RFC 4180 #66

Merged
merged 1 commit into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}