簡體   English   中英

Javascript:在HTML表格中,如何從一列中選擇文本的一部分(與某些正則表達式匹配),然后將其移至下一列?

[英]Javascript: in an HTML table, how to select part of text (matching some regex) from one column, and move it to the next one?

我有一個HTML表,例如2列
第一個中的數據是這樣的:(第二個為空-我將_用作“空”-)

1 (5%)  |  _  
2 (10%) |  _  
3 (15%) |  _

供參考的是:

<table id="my_table" >
<tbody>
<tr>
<td>1 (5%)</td>
<td></td>
</tr>
<tr>
<td>2 (10%)</td>
<td></td>
</tr>
<tr>
<td>3 (15%)</td>
<td></td>
</tr>
</tbody>
</table>

我想要該列的每個單元格(在javascript -greasemonkey-中),
移動括號內的數字(=與正則表達式匹配),
到它旁邊的單元格,即第二列。
因此表將被轉換為

1 | 5%  
2 | 10%  
3 | 15%

這是:

<table id="my_table" >
<tbody>
<tr>
<td>1</td>
<td>5%</td>
</tr>
<tr>
<td>2</td>
<td>10%</td>
</tr>
<tr>
<td>3</td>
<td>15%</td>
</tr>
</tbody>
</table>

如何做到這一點?

這里有一些簡單的函數可以迭代表的行並執行所需的操作。 modTable函數假定傳遞了一個id,但它可能是對該表的引用。

function modTable(id) {
  var table = document.getElementById(id);
  var row, rows = table.rows;
  var cell, cells, text, t0, t1;

  for (var i=0, iLen=rows.length; i<iLen; i++) {
    row = rows[i];
    text = getText(row.cells[0]);

    // Get just leading digits
    t0 = text.replace(/\D+.*/,'');

    // Get just the part in brackets
    t1 = text.replace(/(^.+\()|(\).*$)/g,'');

    // Set new values
    setText(row.cells[0], t0);
    setText(row.cells[1], t1);
  }
}

// Simple helpers for modern and older browsers
// Get textContent of an element
function getText(el) {
  return el.textContent || el.innerText || '';
}

// Set the textContent of an element
function setText(el, text) {
  if (typeof el.textContent == 'string') {
    el.textContent = text;
  } else if (typeof el.innerText == 'string') {
    el.innerText = text;
  }
}

可以通過按鈕調用它:

<button onclick="modTable('my_table');">Modify the table</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM