Skip to content

Commit

Permalink
Surround field values with double quotes if they contain newline char…
Browse files Browse the repository at this point in the history
…acters
  • Loading branch information
ryu1kn committed Oct 15, 2016
1 parent 19c4c53 commit 2bce247
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/field-stringifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ class FieldStringifier {
stringify(value) {
if (typeof value === 'undefined' || value === null) return '';
const str = String(value).trim();
const needsQuotes = str.includes(',') || str.startsWith('"') || str.endsWith('"');
return needsQuotes ? `"${str.replace(/"/g, '""')}"` : str;
return this._needsQuote(str) ? `"${str.replace(/"/g, '""')}"` : str;
}

_needsQuote(str) {
return str.includes(',') || str.includes('\n') || str.startsWith('"') || str.endsWith('"');
}

}
Expand Down
5 changes: 5 additions & 0 deletions test/lib/field-stringifier.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ describe('FieldStringifier', () => {
expect(stringifier.stringify('VALUE,A')).to.eql('"VALUE,A"');
});

it('wraps a field value with double quotes if the field contains newline', () => {
const stringifier = new FieldStringifier();
expect(stringifier.stringify('VALUE\nA')).to.eql('"VALUE\nA"');
});

it('escapes double quotes if it is used on the edge of the field value', () => {
const stringifier = new FieldStringifier();
expect(stringifier.stringify('"VALUE')).to.eql('"""VALUE"');
Expand Down

0 comments on commit 2bce247

Please sign in to comment.