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

1 Answer

0 votes
function splitAndKeep(text, delimSet) {
    if (!text) return [];

    const result = [];
    let start = 0;

    for (let i = 1; i < text.length; i++) {
        const prev = text[i - 1];
        const curr = text[i];

        const prevIsDelim = delimSet.has(prev);
        const currIsDelim = delimSet.has(curr);

        const shouldSplit =
            (prevIsDelim !== currIsDelim) ||          // text ↔ delim
            (prevIsDelim && currIsDelim && prev !== curr); // delim type changed

        if (shouldSplit) {
            result.push(text.slice(start, i));
            start = i;
        }
    }

    // Add final segment
    result.push(text.slice(start));

    return result;
}

const s = "aa==bbb---cccc++++ddddd";
const delimiters = new Set(["=", "-", "+"]);

console.log(splitAndKeep(s, delimiters));



/*
run:

[
  'aa',    '==',
  'bbb',   '---',
  'cccc',  '++++',
  'ddddd'
]

*/

 



answered Mar 10 by avibootz

Related questions

...