Last active
January 10, 2024 20:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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