Improve arrayToCSV to escape quotes in strings and un-quote numeric values.
This commit is contained in:
@ -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'
|
||||
```
|
||||
|
||||
@ -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');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user