如何从第n个分隔符开始将表列拆分为新列

时间:2017-09-11 17:27:33

标签: javascript jquery

我设法创建了一些代码,在斜杠分隔符处将第三列拆分为新列。

我没有做的是将它从第n次(即第二次)发生后分开。 我在互联网上找不到类似的问题,这就是我在这里发帖的原因。

期望的结果应如下:

enter image description here

	function split() {
	    var delimiter = "/";
	    var arr = [];
	    var highest = 0;
	    var columnIndex = "";
	    $('#tbl td:nth-child(3)').each(function() {
	        ColumnIndex = $(this).index();
	        var string = $(this).text();
	        var array = string.split(delimiter);
	        var nbrCharacter = (string.split(delimiter).length - 1) //COUNT OCCURENCES OF CHARACTER
	        var temp = (nbrCharacter > highest) ? highest++ : highest = highest;
	        arr.push(string.split(delimiter));
	    });
	    for (i = 0; i < highest; i++) { //ADD EMPTY COLUMNS
	        $('#tbl').find('tr').each(function() {
	            $(this).find('td').eq(ColumnIndex).after('<td></td>');
	        });
	    }
	    for (i = 0; i < arr.length; i++) { //POPULATE CELLS FROM ARRAY
	        var columnTracker = ColumnIndex
	        for (j = 0; j < arr[i].length; j++) {
	            $('#tbl').find('tr:eq(' + (i + 1) + ')').find('td:eq(' + columnTracker + ')').html(arr[i][j]);
	            columnTracker++
	        }
	    }
	}
th {
    height: 15px;
    min-width: 30px;
    border: 1px solid black;
    font-size: 12px;
    font-family: Courier, monospace;
    padding: 2px 5px 2px 5px;
}

td {
    height: 15px;
    min-width: 30px;
    border: 1px solid black;
    font-size: 12px;
    font-family: Courier, monospace;
    padding: 2px 5px 2px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" onclick="split()">Split</button>

<br>
<br>
<table id="tbl">
    <thead>
        <tr class="tbl-header">
            <th>1</th>
            <th>2</th>
            <th>3</th>
            <th>4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A/B/C</td>
            <td>B/C</td>
            <td>C</td>
            <td></td>
        </tr>
        <tr>
            <td>A/B</td>
            <td>B/C</td>
            <td></td>
            <td>D/E</td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>A/B/C/D</td>
            <td></td>
            <td>C/D/E</td>
            <td>D/E/F</td>
        </tr>
        <tr>
            <td></td>
            <td>B/C/D</td>
            <td>C/D</td>
            <td>D/E/F/G</td>
        </tr>
        <tr>
            <td>A/B/C</td>
            <td>B/C/D/E</td>
            <td>C/D/E/F</td>
            <td></td>
        </tr>
    </tbody>
</table>

0 个答案:

没有答案