/ Published in: JavaScript
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
String.prototype.split2 = function( delimiter, max ) { max = max || Number.Infinity; var arr = []; if( delimiter.constructor != RegExp ) { arr = this.split(delimiter); if( arr.length > max ) { arr.push( arr.splice(max-1, arr.length-max+1).join(delimiter) ); } } else { var old_ix = 0; var match; delimiter.lastIndex = 0; // reset the regexp while( match = delimiter.exec(this) ) { arr.push( this.slice(old_ix, delimiter.lastIndex-match[0].length) ); old_ix = delimiter.lastIndex; if( arr.length+1 == max ) { break; } } arr.push(this.slice(old_ix)); } return arr; }