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

1 Answer

0 votes
function splitAndKeep(text: string, delimSet: Set<string>): string[] {
    if (!text) return [];

    const result: string[] = [];
    let start: number = 0;

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

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

        const shouldSplit: boolean =
            (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

...