Example JavaScript code to parse CSV data

前端 未结 12 1715
梦谈多话
梦谈多话 2020-11-21 07:58

Where could I find some JavaScript code to parse CSV data?

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 08:35

    Here's my simple vanilla JavaScript code:

    let a = 'one,two,"three, but with a comma",four,"five, with ""quotes"" in it.."'
    console.log(splitQuotes(a))
    
    function splitQuotes(line) {
      if(line.indexOf('"') < 0) 
        return line.split(',')
    
      let result = [], cell = '', quote = false;
      for(let i = 0; i < line.length; i++) {
        char = line[i]
        if(char == '"' && line[i+1] == '"') {
          cell += char
          i++
        } else if(char == '"') {
          quote = !quote;
        } else if(!quote && char == ',') {
          result.push(cell)
          cell = ''
        } else {
          cell += char
        }
        if ( i == line.length-1 && cell) {
          result.push(cell)
        }
      }
      return result
    }
    

提交回复
热议问题