Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,393 questions

52,502 answers

573 users

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

...