Skip to content

Instantly share code, notes, and snippets.

@westc
Last active January 10, 2024 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/634d39e4e666c9452b111813d3c8719e to your computer and use it in GitHub Desktop.
Save westc/634d39e4e666c9452b111813d3c8719e to your computer and use it in GitHub Desktop.
partition() - Partitions a string by using the given delimiter. In other words this splits a string while keeping the substring matches that were used to delimit the string.
/**
* Partitions a string by using the given delimiter.
* @param {string} string
* @param {string|RegExp} delimiter
* @returns {(string | (string[] & {input: string, index: number, groups?: Record<string,string>}))[]}
* All items of an even index in the zero-indexed array will be strings while
* all items of an odd index will be `RegExpMatchArray` objects.
*/
function partition(string, delimiter) {
const parts = [];
string.replaceAll(
('string' !== typeof delimiter && !delimiter.global)
? new RegExp(delimiter.source, delimiter.flags + 'g')
: delimiter,
function(...array) {
let last = array.pop(0);
let isLastInput = 'string' === typeof last;
array.input = isLastInput ? last : array.pop(0);
array.groups = isLastInput ? undefined : last;
array.index = array.pop(0);
parts.push(array);
}
);
let end = string.length;
for (let partsIndex = parts.length; -1 < partsIndex--;) {
let part = parts[partsIndex];
let nextEnd = part ? part.index : 0;
let start = part ? nextEnd + part[0].length : 0;
parts.splice(partsIndex + 1, 0, string.slice(start, end));
end = nextEnd;
}
return parts;
}
console.log(partition('hello crazy world!', ' '));
console.log(partition('hello \xA0 crazy,\nlazy world!', /\s+/));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment