【发布时间】:2019-11-02 05:24:24
【问题描述】:
想要通过从 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”确实适用于我的正则表达式。
输出:
【问题讨论】:
-
这个正则表达式甚至应该找到什么?为什么还要使用正则表达式而不是 DOM 方法?
-
我只想在表格元素的结束'>'之后找到第一个html标签的开始,第一个标签应该用'
-
所以...类似于
table.nextSibling?
标签: javascript regex outerhtml