Created
June 15, 2016 09:13
-
-
Save sujith3g/eaddd4b046d4f1da3d573160b68004b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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