Last active
August 1, 2022 20:56
-
-
Save cliffhall/46275ed4d8270b5330e6b58e00ea5e9c to your computer and use it in GitHub Desktop.
Extract substrings of predetermined a length, along with any remainder.
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
/** | |
* String.cordwood | |
* | |
* Add a String prototype method to split string into an array of | |
* substrings of a given length, along with any remainder. | |
* | |
* Example usage: | |
* let paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'; | |
* let stack = paragraph.cordwood(10) | |
* console.log(stack) | |
* // ["The quick ", "brown fox ", "jumps over", " the lazy ", "dog. It ba", "rked."] | |
* | |
* @param cordlen the length of pieces to chop the string into | |
* @returns Array all the equal-sized pieces of the string, and one optional remainder piece shorter than cordlen | |
*/ | |
if (!String.prototype.cordwood) { | |
String.prototype.cordwood = function(cordlen) { | |
if (cordlen === undefined || cordlen > this.length) { | |
cordlen = this.length; | |
} | |
var yardstick = new RegExp(`.{${cordlen}}`, 'g'); | |
var pieces = this.match(yardstick); | |
var accumulated = (pieces.length * cordlen); | |
var modulo = this.length % accumulated; | |
if (modulo) pieces.push(this.slice(accumulated)); | |
return pieces; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add
|.+
to your regex and it'll match the end as well.