Skip to content

Instantly share code, notes, and snippets.

@gilesdring
Last active March 22, 2024 09:56
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 gilesdring/ba6c9a93c25d2ee868be0c7144cd59cc to your computer and use it in GitHub Desktop.
Save gilesdring/ba6c9a93c25d2ee868be0c7144cd59cc to your computer and use it in GitHub Desktop.
Javascript Utilities
/**
* Split a string on whitespace, keeping within a maximum line length
*/
export function splitOnWhitespace(source, maxLength=90) {
// If shorter than the maxLength, just return the source in an array
if (source.length <= maxLength) {
return [source];
}
// Find all space characters
const spaces = [...source.matchAll(/\s+/g)].map(res => res.index);
// Find the largest index before the maxLength
const splitPoint = spaces.filter(i => i < maxLength).pop();
// Return an array comprising...
return [
// the first line (up to the splitPoint)
source.substring(0, splitPoint),
// and a spread of the result of recursing into this function with the rest
...splitOnSpace(source.substring(splitPoint).trim(), maxLength)
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment