Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Split a row of a csv file into
- * @param row
- * @param delimiter
- * @param quotes
- * @returns {Array<string>}
- */
- function splitQuotedCSV(row: string, delimiter: string = ';', quotes: string = '"'): Array<string> {
- if (typeof delimiter !== 'string' || delimiter.length!==1) {
- throw new Error('Delimiter must be one char.');
- }
- if (typeof quotes !== 'string' || quotes.length!==1) {
- throw new Error('A quotes must be one char.');
- }
- if (typeof row !== 'string') {
- throw new Error('The row must be a string')
- }
- const result: Array<string> = [];
- row
- .trim()
- .split(delimiter)
- .reduce((prev, current) => {
- if (prev === null) {
- const startWith = current.startsWith(quotes);
- const endsWith = current.endsWith(quotes);
- if (startWith && !endsWith) {
- prev = current;
- } else {
- result.push(startWith && endsWith ? current.substr(1, current.length -1) : current);
- }
- } else {
- prev+=current;
- if (current.endsWith(quotes)) {
- result.push(prev.substr(1, prev.length-2));
- prev = null;
- }
- }
- return prev;
- }, null);
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement