Split on every second comma in javascript

后端 未结 6 1100
余生分开走
余生分开走 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:48

    This is not a refactored solution, but it works:

    var $dates = '29 July, 2014, 30 July, 2014, 31 July, 2014';
    $dates = $dates.split(',');
    $result = [];
    $dateValue = '';
    
    for($i=0 ; $i<$dates.length ; $i++) {
    if($i % 2 != 0 && $i > 0) {
                $dateValue += ','+$dates[$i];
        $result.push($dateValue);
        $dateValue = '';
    } else {
        $dateValue += $dates[$i];
    }
    }
    
    console.log($result);
    

提交回复
热议问题