Javascript String splitN(n, forward)

Description

Javascript String splitN(n, forward)


//Extend the String object with a function to split a string by every n'th char
//http://stackoverflow.com/questions/14751802/split-a-sting-every-3-characters-from-back-javascript
//http://stackoverflow.com/questions/6259515/javascript-elegant-way-to-split-string-into-segments-n-characters-long
String.prototype.splitN = function (n, forward) {
 forward = typeof forward !== 'undefined' ? forward : true;
 
 if (forward)/*w w w . ja  v  a2  s  .c om*/
  return this.match(new RegExp(".{1," + n.toString() + "}", "g"));
 else
  return this.split(new RegExp("(?=(?:" + Array(n+1).join(".") + ")*$)"))
}



PreviousNext

Related