Created
August 27, 2018 05:52
-
-
Save fazlurr/4895c51a14e7a69c867d3261dfc28673 to your computer and use it in GitHub Desktop.
Text Splitter
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
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