Posted By

aadsm on 10/04/09


Tagged

max split


Versions (?)

Split with a sane second argument behaviour


 / Published in: JavaScript
 

  1. String.prototype.split2 = function( delimiter, max )
  2. {
  3. max = max || Number.Infinity;
  4. var arr = [];
  5.  
  6. if( delimiter.constructor != RegExp )
  7. {
  8. arr = this.split(delimiter);
  9. if( arr.length > max )
  10. {
  11. arr.push( arr.splice(max-1, arr.length-max+1).join(delimiter) );
  12. }
  13. }
  14. else
  15. {
  16. var old_ix = 0;
  17. var match;
  18.  
  19. delimiter.lastIndex = 0; // reset the regexp
  20. while( match = delimiter.exec(this) )
  21. {
  22. arr.push( this.slice(old_ix, delimiter.lastIndex-match[0].length) );
  23. old_ix = delimiter.lastIndex;
  24. if( arr.length+1 == max ) { break; }
  25. }
  26.  
  27. arr.push(this.slice(old_ix));
  28. }
  29.  
  30. return arr;
  31. }

Report this snippet  

You need to login to post a comment.