Improve arrayToCSV to escape quotes in strings and un-quote numeric values.

This commit is contained in:
Dan Howe
2019-03-18 23:16:19 +10:00
parent 9fbb61c79c
commit 74e212fb9a
2 changed files with 5 additions and 1 deletions

View File

@ -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'
```

View File

@ -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');
});