Skip to content

Instantly share code, notes, and snippets.

@fazlurr
Created August 27, 2018 05:52
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 fazlurr/4895c51a14e7a69c867d3261dfc28673 to your computer and use it in GitHub Desktop.
Save fazlurr/4895c51a14e7a69c867d3261dfc28673 to your computer and use it in GitHub Desktop.
Text Splitter
export const textSplitter = (str, l) => {
const strs = [];
while (str.length > l) {
const newlinePosition = str.substring(0, l).lastIndexOf('\n');
const isGotNewline = newlinePosition !== -1;
// If there is a newline within the text range, then get the newline position
let pos = isGotNewline ? newlinePosition : str.substring(0, l).lastIndexOf(' ');
pos = pos <= 0 ? l : pos;
strs.push(str.substring(0, pos));
if (isGotNewline) {
strs.push('');
}
let i = isGotNewline ? str.indexOf('\n', pos) + 1 : str.indexOf(' ', pos) + 1;
if (i < pos || i > pos + l) i = pos;
str = str.substring(i);
}
strs.push(str);
return strs;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment