Home >Web Front-end >JS Tutorial >How to Parse a CSV String with Commas Inside Quoted Fields in JavaScript?
This JavaScript snippet will enable you to parse a CSV string that has commas within the data, while ignoring commas inside quoted fields:
const parseCSV = (csvString) => { const rows = csvString.split("\n"); const result = []; for (const row of rows) { const values = []; let currentField = ""; let inQuotes = false; for (const char of row) { if (char === '"' && currentField.length === 0) { inQuotes = !inQuotes; } else if (char === "," && !inQuotes) { values.push(currentField); currentField = ""; } else { currentField += char; } } if (currentField.length > 0) { values.push(currentField); } result.push(values); } return result; }; const csvString = 'string, duppi, du, 23, lala'; console.log(parseCSV(csvString));
This solution tackles your query by employing a character-by-character examination of the CSV string. Each time a comma is detected and the string isn't inside a quoted field, a new field is generated. When a double quotation mark is encountered at the beginning of a field, it indicates the start of a quoted field. Another double quotation mark outside a quoted field signifies the end of that field. By constantly examining the values, this technique precisely partitions the CSV string into individual fields, taking into account quoted areas.
The above is the detailed content of How to Parse a CSV String with Commas Inside Quoted Fields in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!