想要通过从 table 的 outerHTML 中提取来获取 table 定义的 HTML,寻找 '> 不管 <' 的索引
尝试了几种模式和 match() 但没有运气。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<!-- <thead> not on same line as <table> -->
<table id="t1" border="1">
<thead>
<tr> <th colspan="2">1</th><th colspan="3">22 </th></tr>
<tr> <th>1</th><th data-rotate>22</th><th data-rotate>333</th><th>4444</th><th>5555555</th></tr>
</thead>
<tr><td>aaaaaaa</td><td>bbbbbbbbb</td><td>cccccccccc</td><td>ddddd<br>ddddddd</td><td>dddddddddddd</td></tr>
</table>
<!-- <thead> on same line as <table> -->
<table id="t2" border="1" > <thead>
<tr> <th colspan="2">1</th><th colspan="3">22 </th></tr>
<tr> <th>1</th><th data-rotate>22</th><th data-rotate>333</th><th>4444</th><th>5555555</th></tr>
</thead>
<tr><td>aaaaaaa</td><td>bbbbbbbbb</td><td>cccccccccc</td><td>ddddd<br>ddddddd</td><td>dddddddddddd</td></tr>
</table>
<p>
<div id="out1"></div>
<p>
<div id="out2"></div>
<script>
/*****************************************
* want to get the HTML for a table definition
* by extracting <table ...> from outer html, looking
* for the index of '> whatever <'
*****************************************/
var m, t, oh, index;
/*****************************************
* does not work
*****************************************/
t = document.getElementById('t1');
oh = t.outerHTML;
index = oh.search(/\> *</); // what is wrong with regex
document.getElementById('out1').innerHTML = htmlentity(oh.substring(0, index + 1));
/*****************************************
* works
*****************************************/
t = document.getElementById('t2');
oh = t.outerHTML;
index = oh.search(/\> *\</);
document.getElementById('out2').innerHTML = htmlentity(oh.substring(0, index + 1));
function htmlentity(value) {
value = value.replace(/&/gi, "&");
value = value.replace(/</gi, "<");
value = value.replace(/>/gi, ">");
value = value.replace(/"/gi, """);
value = value.replace(/'/gi, "'");
return value;
}
</script>
</body>
</html>
```
第一个表定义“t1”不适用于我的正则表达式。第二个表定义“t2”确实适用于我的正则表达式。
输出: