Skip to content

Instantly share code, notes, and snippets.

@ifukazoo
Created April 20, 2014 01:59
Show Gist options
  • Select an option

  • Save ifukazoo/11102957 to your computer and use it in GitHub Desktop.

Select an option

Save ifukazoo/11102957 to your computer and use it in GitHub Desktop.
String.prototype.splitN = function (n) {
var a = [];
var begin = 0;
var i = 0;
for (; i < this.length; i++) {
if (i !== 0 && i % n == 0) {
a.push(this.substring(begin, i));
begin = i;
}
}
a.push(this.substring(begin));
return a;
}
console.log("abcdefg".splitN(0).toString() === ['abcdefg'].toString());
console.log("abcdefg".splitN(1).toString() === ['a', 'b', 'c', 'd', 'e', 'f', 'g'].toString());
console.log("abcdefg".splitN(2).toString() === ['ab', 'cd', 'ef', 'g'].toString());
console.log("abcdefg".splitN(10).toString() === ['abcdefg'].toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment