【发布时间】:2011-02-27 08:24:27
【问题描述】:
我正在尝试找到一种方法,使用 javascript 或 jquery 编写一个函数,该函数从页面中删除所有 html 标签,只给我这个页面的纯文本。
如何做到这一点?有什么想法吗?
【问题讨论】:
-
你想要一个返回
<body>的文本内容的字符串,然后呢?
标签: javascript jquery html
我正在尝试找到一种方法,使用 javascript 或 jquery 编写一个函数,该函数从页面中删除所有 html 标签,只给我这个页面的纯文本。
如何做到这一点?有什么想法吗?
【问题讨论】:
<body>的文本内容的字符串,然后呢?
标签: javascript jquery html
IE 和 WebKit
document.body.innerText
其他:
document.body.textContent
(根据 Amr ElGarhy 的建议)
大多数 js 框架都实现了跨浏览器的方式来执行此操作。这通常是这样实现的:
text = document.body.textContent || document.body.innerText;
似乎 WebKit 使用 textContent 保留了一些格式,而使用 innerText 剥离了所有内容。
【讨论】:
这取决于您要保留多少格式。但是使用 jQuery 你可以这样做:
jQuery(document.body).text();
【讨论】:
textContent 或 innerText 的唯一问题是它们可以将相邻节点的文本挤在一起, 它们之间没有任何空白。
如果这很重要,您可以通过 body 或其他容器进行诅咒,并以数组的形式返回文本, 并用空格或换行符将它们连接起来。
document.deepText= function(hoo){
var A= [], tem, tx;
if(hoo){
hoo= hoo.firstChild;
while(hoo!= null){
if(hoo.nodeType== 3){
tx= hoo.data || '';
if(/\S/.test(tx)) A[A.length]= tx;
}
else A= A.concat(document.deepText(hoo));
hoo= hoo.nextSibling;
}
}
return A;
}
alert(document.deepText(document.body).join(' '))
// return document.deepText(document.body).join('\n')
【讨论】:
nodeType of 4 (CDATA) 可能是个好主意,以防有人将他们的文本包含在其中。 (至少 jQuery 是这样做的。)
我必须将 HTML 电子邮件中的富文本转换为纯文本。以下在 IE 中对我有用(obj 是一个 jQuery 对象):
function getTextFromHTML(obj) {
var ni = document.createNodeIterator(obj[0], NodeFilter.SHOW_TEXT, null, false);
var nodeLine = ni.nextNode(); // go to first node of our NodeIterator
var plainText = "";
while (nodeLine) {
plainText += nodeLine.nodeValue + "\n";
nodeLine = ni.nextNode();
}
return plainText;
}
【讨论】:
使用htmlClean。
【讨论】:
我会使用:
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"></script>
<script type="text/javascript">
jQuery.fn.stripTags = function() { return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') ); };
jQuery('head').stripTags();
$(document).ready(function() {
$("img").each(function() {
jQuery(this).remove();
});
});
</script>
这将不会释放任何样式,但会删除所有标签。
这是你想要的吗?
[EDIT] 现已编辑为包括删除图像标签[/EDIT]
【讨论】: