Skip to content

Instantly share code, notes, and snippets.

@donavon
Last active January 30, 2021 15:58
Show Gist options
  • Save donavon/b91a41978dff3a7293c58584a0d56796 to your computer and use it in GitHub Desktop.
Save donavon/b91a41978dff3a7293c58584a0d56796 to your computer and use it in GitHub Desktop.
segmentize
const segmentize = (str: string, maxLength: number): string[] => {
const regex = new RegExp(`.{1,${maxLength}}`, 'g');
return str.match(regex) ?? [];
};
const segmentize = (
str: string,
maxLength: number,
segments: string[] = []
): string[] => {
if (str.length > maxLength) {
const segment = str.substr(0, maxLength);
const rest = str.substr(maxLength);
return segmentize(rest, maxLength, [...segments, segment]);
}
return [...segments, str];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment