[英]Javascript: in an HTML table, how to select part of text (matching some regex) from one column, and move it to the next one?
I have an HTML table which eg, 2 columns 我有一个HTML表,例如2列
and the data in the 1st one are like this: (the 2nd is empty -I use _ as "empty"-) 第一个中的数据是这样的:(第二个为空-我将_用作“空”-)
1 (5%) | _
2 (10%) | _
3 (15%) | _
which, for reference is: 供参考的是:
<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>
I want (in javascript -greasemonkey- ) for each cell of that column, 我想要该列的每个单元格(在javascript -greasemonkey-中),
to move the number which is inside the parentheses (=with regex matching), 移动括号内的数字(=与正则表达式匹配),
to the cell next to it, ie to the 2nd column. 到它旁边的单元格,即第二列。
Therefore the table will be converted to 因此表将被转换为
1 | 5%
2 | 10%
3 | 15%
which is: 这是:
<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>
How can this be achieved? 如何做到这一点?
Here are some simple functions to iterate over the table's row and do what you want. 这里有一些简单的函数可以迭代表的行并执行所需的操作。 The modTable function assumes an id is passed, but it could be a reference to the table instead. 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;
}
}
It can be called from a button: 可以通过按钮调用它:
<button onclick="modTable('my_table');">Modify the table</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.