How to split a string on multiple single‑character delimiters (and keep them) in JavaScript

1 Answer

0 votes
function splitKeepDelims(s, delimiters) {
    const result = [];

    // Build regex: e.g. ",;|" → /([,;|])/g
    const pattern = new RegExp("([" + delimiters.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "])", "g");

    let lastEnd = 0;

    for (const match of s.matchAll(pattern)) {
        const index = match.index;

        // Add text before delimiter
        if (index > lastEnd) {
            result.push(s.substring(lastEnd, index));
        }

        // Add the delimiter itself
        result.push(match[0]);

        lastEnd = index + match[0].length;
    }

    // Add remaining text after last delimiter
    if (lastEnd < s.length) {
        result.push(s.substring(lastEnd));
    }

    return result;
}

const parts = splitKeepDelims("aa,bbb;cccc|ddddd", ",;|");

for (const p of parts) {
    process.stdout.write("[" + p + "] ");
}



/*
run:

[aa] [,] [bbb] [;] [cccc] [|] [ddddd] 

*/

 



answered Mar 9 by avibootz

Related questions

...