Skip to content

Instantly share code, notes, and snippets.

@sujith3g
Created June 15, 2016 09:13
Show Gist options
  • Save sujith3g/eaddd4b046d4f1da3d573160b68004b8 to your computer and use it in GitHub Desktop.
Save sujith3g/eaddd4b046d4f1da3d573160b68004b8 to your computer and use it in GitHub Desktop.
escapeCsv = function(options) {
this.options = options || {
delimiter : ",",
quote : '"',
escape : '"'
};
};
escapeCsv.prototype.escape = function(field) {
if (field) {
escape = this.options.escape;
quote = this.options.quote;
delimiter = this.options.delimiter;
containsdelimiter = field.indexOf(delimiter) >= 0;
containsQuote = field.indexOf(quote) >= 0;
containsEscape = field.indexOf(escape) >= 0 && (escape !== quote);
containsLinebreak = field.indexOf('\r') >= 0 || field.indexOf('\n') >= 0;
shouldQuote = containsQuote || containsdelimiter || containsLinebreak || this.options.quoted || this.options.quotedString;
if (shouldQuote && containsEscape) {
regexp = escape === '\\' ? new RegExp(escape + escape, 'g') : new RegExp(escape, 'g');
field = field.replace(regexp, escape + escape);
}
if (containsQuote) {
regexp = new RegExp(quote, 'g');
field = field.replace(regexp, escape + quote);
}
if (shouldQuote) {
field = quote + field + quote;
}
}
return field;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment