Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Last active January 11, 2018 23:30
Show Gist options
  • Save aleclarson/198a4a878d550aeb5d79a856ea752c96 to your computer and use it in GitHub Desktop.
Save aleclarson/198a4a878d550aeb5d79a856ea752c96 to your computer and use it in GitHub Desktop.
Split a string every N characters (starting from the end)
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]
}
@aleclarson
Copy link
Author

A nicer API would be positive n to indicate "start from beginning" and negative n to indicate "start from end".

splitEveryN('abcde', 2) // => ['ab', 'cd', 'e']
splitEveryN('abcde', -2) // => ['a', 'bc', 'de']

@aleclarson
Copy link
Author

splitEveryNth may be a better name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment