有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
如果你想保留链接和内容结构(h1、h2等),那么你应该检查TextVersionJS。你可以将它与任何HTML一起使用,尽管它是为了将HTML电子邮件转换为纯文本而创建的。
用法很简单。例如,在node.js中:
var createTextVersion = require("textversionjs");
var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>";
var textVersion = createTextVersion(yourHtml);
或者在浏览器中使用纯js:
<script src="textversion.js"></script>
<script>
var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>";
var textVersion = createTextVersion(yourHtml);
</script>
它也适用于require.js:
define(["textversionjs"], function(createTextVersion) {
var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>";
var textVersion = createTextVersion(yourHtml);
});
其他回答
作为jQuery方法的扩展,如果字符串可能不包含HTML(例如,如果您试图从表单字段中删除HTML)
jQuery(html).text();
如果没有HTML,将返回空字符串
Use:
jQuery('<p>' + html + '</p>').text();
相反
更新:正如评论中所指出的,在某些情况下,如果攻击者可能影响html的值,则此解决方案将执行html中包含的javascript,请使用不同的解决方案。
在尝试了所有提到的答案后,如果不是所有答案都有边缘案例,也不能完全支持我的需求。
我开始探索php是如何做到这一点的,并在这里遇到了复制strip_tags方法的php.js库:http://phpjs.org/functions/strip_tags/
输入元素仅支持单行文本:
文本状态表示元素值的单行纯文本编辑控件。
function stripHtml(str) {
var tmp = document.createElement('input');
tmp.value = str;
return tmp.value;
}
更新:这是预期的
function stripHtml(str) {
// Remove some tags
str = str.replace(/<[^>]+>/gim, '');
// Remove BB code
str = str.replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, '$2 ');
// Remove html and line breaks
const div = document.createElement('div');
div.innerHTML = str;
const input = document.createElement('input');
input.value = div.textContent || div.innerText || '';
return input.value;
}
对于转义字符,也可以使用模式匹配:
myString.replace(/((<)|(<)(?:.|\n)*?(>)|(>))/gm, '');
这应该可以在任何Javascript环境(包括NodeJS)上完成工作。
const text = `
<html lang="en">
<head>
<style type="text/css">*{color:red}</style>
<script>alert('hello')</script>
</head>
<body><b>This is some text</b><br/><body>
</html>`;
// Remove style tags and content
text.replace(/<style[^>]*>.*<\/style>/gm, '')
// Remove script tags and content
.replace(/<script[^>]*>.*<\/script>/gm, '')
// Remove all opening, closing and orphan HTML tags
.replace(/<[^>]+>/gm, '')
// Remove leading spaces and repeated CR/LF
.replace(/([\r\n]+ +)+/gm, '');