Last active
March 22, 2024 09:56
-
-
Save gilesdring/ba6c9a93c25d2ee868be0c7144cd59cc to your computer and use it in GitHub Desktop.
Javascript Utilities
This file contains hidden or 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
/** | |
* 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