Split on every second comma in javascript

后端 未结 6 1104
余生分开走
余生分开走 2021-01-18 01:05

For string:

\'29 July, 2014, 30 July, 2014, 31 July, 2014\'

How can I split on every second comma in the string? So that my results are:

6条回答
  •  不知归路
    2021-01-18 01:43

    I know it's almost two years ago.

    This function is reusable.

    String.prototype isn't necessary to make it work.. But it's easy..

    String.prototype.splitEvery = function ( splitter, every ){
    
        var array = this.split( splitter), newString = '', thisSplitter; 
    
        $.each( array, function( index, elem ){ 
    
            thisSplitter = ( index < array.length - 1 || index % every === 0 ) ? '' : splitter;
    
            newString += elem + thisSplitter;                                                               
        });          
    
        return newString;                                                                                   
    };  
    
    
    var dateString = '29 July, 2014, 30 July, 2014, 31 July, 2014';
    

    The usage in this case is:

    dateString.splitEvery( ',', 2 );
    

    First parameter is the split, second is how many is between each.

    Result are:

    29 July 2014, 30 July 2014, 31 July 2014
    

提交回复
热议问题