Skip to content

Instantly share code, notes, and snippets.

@cliffhall
Last active August 1, 2022 20:56
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 cliffhall/46275ed4d8270b5330e6b58e00ea5e9c to your computer and use it in GitHub Desktop.
Save cliffhall/46275ed4d8270b5330e6b58e00ea5e9c to your computer and use it in GitHub Desktop.
Extract substrings of predetermined a length, along with any remainder.
/**
* 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;
};
}
@dr-skot
Copy link

dr-skot commented Jul 31, 2022

Add |.+ to your regex and it'll match the end as well.

"covfefe".match(/..|.+/g)
[ 'co', 'vf', 'ef', 'e' ]
if (!String.prototype.cordwood) {
  String.prototype.cordwood = function(cordlen) {
    if (!cordlen || cordlen < 0) cordlen = this.length;
    const yardstick = new RegExp(`.{${cordlen}}|.+`, 'g');
    return this.match(yardstick);
 };
}

@cliffhall
Copy link
Author

Nice one, @dr-skot!

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