Last active
January 11, 2018 23:30
-
-
Save aleclarson/198a4a878d550aeb5d79a856ea752c96 to your computer and use it in GitHub Desktop.
Split a string every N characters (starting from the end)
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
function splitEveryN(str, n) { | |
const len = str.length | |
if (len > n) { | |
let i = len - n | |
const parts = [] | |
while (true) { | |
parts.push(str.substr(i, n)) | |
if (i <= n) { | |
parts.push(str.substr(0, i)) | |
return parts.reverse() | |
} | |
i -= n | |
} | |
} | |
return [str] | |
} |
splitEveryNth
may be a better name
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A nicer API would be positive
n
to indicate "start from beginning" and negativen
to indicate "start from end".