aboutsummaryrefslogtreecommitdiff
path: root/frontend/src/app/_services/csv-parse.service.ts
blob: e44af2386023f72cb8cebb4a74480c0cee8fbd63 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { Injectable } from "@angular/core";
@Injectable({ providedIn: 'root' })
export class CsvParseService {

  csvToArray(strData: string, strDelimiter: string): string[][] {
    strDelimiter = (strDelimiter || ",");

    let objPattern = new RegExp(
      (
        // Delimiters.
        "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

        // Quoted fields.
        "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

        // Standard fields.
        "([^\"\\" + strDelimiter + "\\r\\n]*))"
      ),
      "gi"
    );

    let arrData: string[][] = [[]];

    let arrMatches = null;

    while (arrMatches = objPattern.exec(strData)) {

      let strMatchedDelimiter = arrMatches[1];

      if (
        strMatchedDelimiter.length &&
        strMatchedDelimiter !== strDelimiter
      ) {
        arrData.push([]);
      }

      let strMatchedValue;

      if (arrMatches[2]) {
        strMatchedValue = arrMatches[2].replace(
          new RegExp("\"\"", "g"),
          "\""
        );
      } else {
        strMatchedValue = arrMatches[3];
      }

      //if (strMatchedValue.length > 0)
        arrData[arrData.length - 1].push(strMatchedValue);
    }

    return (arrData);
  }
}