Browse Source

Add Custom Quote Character to unparse (#329)

pull/325/merge
Prayash Mohapatra 8 years ago committed by Sergi Almacellas Abellana
parent
commit
32cc6cad64
  1. 12
      papaparse.js
  2. 6
      tests/test-cases.js

12
papaparse.js

@ -243,8 +243,13 @@
/** newline character(s) */ /** newline character(s) */
var _newline = '\r\n'; var _newline = '\r\n';
/** quote character */
var _quoteChar = '"';
unpackConfig(); unpackConfig();
var quoteCharRegex = new RegExp(_quoteChar, 'g');
if (typeof _input === 'string') if (typeof _input === 'string')
_input = JSON.parse(_input); _input = JSON.parse(_input);
@ -300,6 +305,9 @@
if (typeof _config.newline === 'string') if (typeof _config.newline === 'string')
_newline = _config.newline; _newline = _config.newline;
if (typeof _config.quoteChar === 'string')
_quoteChar = _config.quoteChar;
if (typeof _config.header === 'boolean') if (typeof _config.header === 'boolean')
_writeHeader = _config.header; _writeHeader = _config.header;
} }
@ -368,7 +376,7 @@
if (typeof str === 'undefined' || str === null) if (typeof str === 'undefined' || str === null)
return ''; return '';
str = str.toString().replace(/"/g, '""'); str = str.toString().replace(quoteCharRegex, _quoteChar+_quoteChar);
var needsQuotes = (typeof _quotes === 'boolean' && _quotes) var needsQuotes = (typeof _quotes === 'boolean' && _quotes)
|| (_quotes instanceof Array && _quotes[col]) || (_quotes instanceof Array && _quotes[col])
@ -377,7 +385,7 @@
|| str.charAt(0) === ' ' || str.charAt(0) === ' '
|| str.charAt(str.length - 1) === ' '; || str.charAt(str.length - 1) === ' ';
return needsQuotes ? '"' + str + '"' : str; return needsQuotes ? _quoteChar + str + _quoteChar : str;
} }
function hasAny(str, substrings) function hasAny(str, substrings)

6
tests/test-cases.js

@ -1162,6 +1162,12 @@ var UNPARSE_TESTS = [
input: [{ "Col1": "a", "Col2": null, "Col3": "c" }], input: [{ "Col1": "a", "Col2": null, "Col3": "c" }],
expected: 'Col1,Col2,Col3\r\na,,c' expected: 'Col1,Col2,Col3\r\na,,c'
}, },
{
description: "Custom quote character (single quote)",
input: [['a,d','b','c']],
config: { quoteChar: "'"},
expected: "'a,d',b,c"
},
{ {
description: "Don't print header if header:false option specified", description: "Don't print header if header:false option specified",
input: [{ "Col1": "a", "Col2": "b", "Col3": "c" }, { "Col1": "d", "Col2": "e", "Col3": "f" }], input: [{ "Col1": "a", "Col2": "b", "Col3": "c" }, { "Col1": "d", "Col2": "e", "Col3": "f" }],

Loading…
Cancel
Save