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]
*/