Home > Web Front-end > JS Tutorial > How to Correctly Parse CSV Strings with Commas in JavaScript?

How to Correctly Parse CSV Strings with Commas in JavaScript?

Linda Hamilton
Release: 2024-12-03 02:51:14
Original
1023 people have browsed it

How to Correctly Parse CSV Strings with Commas in JavaScript?

How to Handle Commas in CSV Data When Parsing Strings in JavaScript

When dealing with CSV strings containing data that also includes commas, parsing can be tricky. Splitting the string on commas (",") alone won't give you the desired output if some values are enclosed in quotation marks. Here's how you can parse such CSV strings while respecting quotation marks:

// Regex to validate a CSV string:
const re_valid = /^\s*(?:'[^'\]*(?:\[\S\s][^'\]*)*'|"[^"\]*(?:\[\S\s][^"\]*)*"|[^,'"\s\]*(?:\s+[^,'"\s\]+)*)\s*(?:,\s*(?:'[^'\]*(?:\[\S\s][^'\]*)*'|"[^"\]*(?:\[\S\s][^"\]*)*"|[^,'"\s\]*(?:\s+[^,'"\s\]+)*)*\s*)*$/;

// Regex to parse one value from a valid CSV string:
const re_value = /(?!\s*$)\s*(?:'([^'\]*(?:\[\S\s][^'\]*)*)'|"([^"\]*(?:\[\S\s][^"\]*)*)"|([^,'"\s\]*(?:\s+[^,'"\s\]+)*)|)\s*(?:,|$)/g;

function CSVtoArray(text) {
    if (!re_valid.test(text)) return null;
    const a = [];
    text.replace(re_value, (m0, m1, m2, m3) => {
        if      (m1 !== undefined) a.push(m1.replace(/\'/g, "'"));
        else if (m2 !== undefined) a.push(m2.replace(/\"/g, '"'));
        else if (m3 !== undefined) a.push(m3);
        return '';
    });
    if (/,\s*$/.test(text)) a.push('');
    return a;
}
Copy after login

With this approach, you can accurately parse CSV strings, including those with mixed types and escaped characters, while respecting quotation marks.

The above is the detailed content of How to Correctly Parse CSV Strings with Commas in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template