Advertisement
Guest User

Untitled

a guest
Apr 29th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. /**
  2. * Split a row of a csv file into
  3. * @param row
  4. * @param delimiter
  5. * @param quotes
  6. * @returns {Array<string>}
  7. */
  8. function splitQuotedCSV(row: string, delimiter: string = ';', quotes: string = '"'): Array<string> {
  9. if (typeof delimiter !== 'string' || delimiter.length!==1) {
  10. throw new Error('Delimiter must be one char.');
  11. }
  12. if (typeof quotes !== 'string' || quotes.length!==1) {
  13. throw new Error('A quotes must be one char.');
  14. }
  15. if (typeof row !== 'string') {
  16. throw new Error('The row must be a string')
  17. }
  18.  
  19. const result: Array<string> = [];
  20. row
  21. .trim()
  22. .split(delimiter)
  23. .reduce((prev, current) => {
  24. if (prev === null) {
  25. const startWith = current.startsWith(quotes);
  26. const endsWith = current.endsWith(quotes);
  27. if (startWith && !endsWith) {
  28. prev = current;
  29. } else {
  30. result.push(startWith && endsWith ? current.substr(1, current.length -1) : current);
  31. }
  32. } else {
  33. prev+=current;
  34. if (current.endsWith(quotes)) {
  35. result.push(prev.substr(1, prev.length-2));
  36. prev = null;
  37. }
  38. }
  39. return prev;
  40. }, null);
  41.  
  42. return result;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement