diff --git a/snippets/arrayToCSV.md b/snippets/arrayToCSV.md index 5f9c241b0..a8a499087 100644 --- a/snippets/arrayToCSV.md +++ b/snippets/arrayToCSV.md @@ -8,10 +8,11 @@ Omit the second argument, `delimiter`, to use a default delimiter of `,`. ```js const arrayToCSV = (arr, delimiter = ',') => - arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n'); + arr.map(v => v.map(x => isNaN(x) ? `"${x.replace(/"/g, '""')}"` : x ).join(delimiter)).join('\n'); ``` ```js arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"' arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"' +arrayToCSV([['a', '"b" great'], ['c', 3.1415]]); // '"a","""b"" great"\n"c",3.1415' ``` diff --git a/test/arrayToCSV.test.js b/test/arrayToCSV.test.js index c9d36d114..cdc95c87a 100644 --- a/test/arrayToCSV.test.js +++ b/test/arrayToCSV.test.js @@ -10,3 +10,6 @@ test('arrayToCSV works with default delimiter', () => { test('arrayToCSV works with custom delimiter', () => { expect(arrayToCSV([['a', 'b'], ['c', 'd']], ';')).toBe('"a";"b"\n"c";"d"'); }); +test('arrayToCSV escapes quotes and doesn\'t quote numbers', () => { + expect(arrayToCSV([['a', '"b" great'], ['c', 3.1415]])).toBe('"a","""b"" great"\n"c",3.1415'); +});