LoginSignup
2
0

More than 5 years have passed since last update.

csv をパースする JavaScript

Last updated at Posted at 2019-03-02

車輪の再発明です

CSV の仕様

RFC 4180

改行は CRLF でなければならないそうです。

実装例

function parseCSV(d) {
    let t = d.replace(/\r\n$/u, '')
    const r = [[]]
    let c = 0
    let l, m, n
    while ([l, m, n] = /^(|[^",](?:[^,\r]|\r[^,\n])*\r?|"(?:[^"]|"")*")(,|\r\n|$)/u.exec(t)) {
        if ('"' === m[0] && '"' === m[m.length - 1]) m = m.slice(1, -1)
        r[c].push(m.replace(/""/gu, '"'))
        if (!n) break
        if (',' !== n) r[++c] = []
        t = t.substring(l.length)
    }
    return r
}

実装例2

\n\r も改行とみなす方が便利かと思います。

function parseCSV(d) {
    let t = d.replace(/(\r?\n|\r)$/u, '')
    const r = [[]]
    let c = 0
    let l, m, n
    while ([l, m, n] = /^(|[^",][^,\r\n]*|"(?:[^"]|"")*")(,|\r?\n|\r|$)/u.exec(t)) {
        if ('"' === m[0] && '"' === m[m.length - 1]) m = m.slice(1, -1)
        r[c].push(m.replace(/""/gu, '"'))
        if (!n) break
        if (',' !== n) r[++c] = []
        t = t.substring(l.length)
    }
    return r
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0