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
Linda HamiltonOriginal
2024-12-03 02:51:14968browse

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;
}

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!

Statement:
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