Javascript parse CSV

Date: 2021-12-07
function* getLinesFromString(source) {
    let lines = String(source || "").matchAll(/^.*$/gm);
    for (const [line] of lines) yield line;
}

function* getCsvValueFromLine(source, separator = ",") {
    const line = String(source || "");
    let inString = false;
    let start = 0;

    for (let i = 0; i < line.length; i++) {
        const char = line[i];
        const nextChar = line[i + 1];

        if (char === '"') {
            inString = !inString;
        } else if (!inString && char === separator) {
            yield line.substring(start, i);
            start = i + 1;
        } else if (i + 1 === line.length) {
            yield line.substring(start, i + 1);
        }
    }
}

function decodeValue(val) {
    return val.trim().replace(/^"|"$/g, "").replace(/""/g, '"');
}

function trimChars(s, c) {
    if (c === "]") c = "\\]";
    if (c === "^") c = "\\^";
    if (c === "\\") c = "\\\\";
    return s.replace(new RegExp("^[" + c + "]+|[" + c + "]+$", "g"), "");
}

const csv = `value1,"value,with,comma","value ""with quotes"" inside",value4`;
for (const line of getLinesFromString(csv)) {
    console.log("======================");
    for (const value of getCsvValueFromLine(line, ",")) {
        console.log("value:", decodeValue(value));
    }
}
57750cookie-checkJavascript parse CSV