Return to Snippet

Revision: 18607
at October 5, 2009 03:22 by aadsm


Updated Code
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;
}

Revision: 18606
at October 4, 2009 14:44 by aadsm


Initial Code
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).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;
}

Initial URL

                                

Initial Description

                                

Initial Title
Split with a sane second argument behaviour

Initial Tags

                                

Initial Language
JavaScript