我有一个包含来自外部 HTML 页面的 responseText 的变量:
textFromFile = myRequest.responseText;
我怎样才能删除正文标签之外的所有内容? 我可以使用 Regex 删除字符串 (textFromFile) 中的所有 HTML 标记,但在此之前,如果有人可以帮助我删除正文标记之外的所有字符(换句话说,我将不胜感激,只需将字符串/单词保留在 HTML 页面的 body 标签内即可)。
----编辑部分----
我正在阅读的 HTML 文件是:
<html>
<head> title </head>
<body>
<p> Hello World! <br/>
<a href = ”link.html”> Click <b> here </b> </a> <br/>
Goodbye world!
</p>
</body>
</html>
当我申请时:
var doc = new DOMParser().parseFromString(myRequest.responseText, "text/html");
alert(doc.body.innerHTML);
响应是:
title
<p> Hello World! <br>
<a href="”link.html”"> Click <b> here </b> </a> <br>
Goodbye world!
</p>
这不应该是这种情况,因为“标题”在正文标签之外。
最佳答案
使用 DOM 解析器解析 HTML:
var doc = new DOMParser().parseFromString(myRequest.responseText, "text/html");
然后简单地使用innerHTML
(或outerHTML
):
doc.body.innerHTML;
var string = "<!DOCTYPE html><title>Title</title><p>Hello</p>",
doc = new DOMParser().parseFromString(string, "text/html");
document.getElementById('inner').textContent = doc.body.innerHTML;
document.getElementById('outer').textContent = doc.body.outerHTML;
pre {
background: #ddd;
font-family: monospace;
padding: .5em;
}
The inner HTML of <body> is:
<pre id="inner"></pre>
The outer HTML of <body> is:
<pre id="outer"></pre>
关于javascript - 删除 body 标签之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35262172/