To create CSV fields in JavaSCript, here's some a method that will work:
// Escapes a String such that it can be used in a CSV cell // Based on Apache Commons StringEscapeUtils library // (see Wikipedia and RFC 4180) // Parameters: // input - the input CSV column String, may be null // Returns: // the input String, enclosed in double quotes // if the value contains a comma, newline or double quote, // '' if null string input. // Also, any double quote characters in the value are escaped with another double quote.
var QUOTE = '"', ESCAPED_QUOTE = """", CHARS_THAT_MUST_BE_QUOTED = [ ',' , '"' , '\n' ];
// Escapes a String such that it can be used in a CSV cell // Based on Apache Commons StringEscapeUtils library // (see Wikipedia and RFC 4180) // Parameters: // input - the input CSV column String, may be null // Returns: // the input String, enclosed in double quotes // if the value contains a comma, newline or double quote, // '' if null string input. // Also, any double quote characters in the value // are escaped with another double quote. var QUOTE = '"', ESCAPED_QUOTE = "\"\"", CHARS_THAT_MUST_BE_QUOTED = [ ',' , '"' , '\n' ]; var escapeCSVCell = function(c) { if ( c.indexOf( QUOTE ) > -1 ) c = c.replace(/"/g, ESCAPED_QUOTE ); $.each(CHARS_THAT_MUST_BE_QUOTED,function(i,char){ if (c.indexOf(char) > -1) { c = QUOTE + c + QUOTE; return false; } }); return cc; } // Call escapeCSVCell on each CSV field
}
// Call escapeCSVCell on each CSV field