有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
对于转义字符,也可以使用模式匹配:
myString.replace(/((<)|(<)(?:.|\n)*?(>)|(>))/gm, '');
其他回答
myString.replace(/<[^>]*>?/gm, '');
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
var div = document.getElementsByTagName('div');
for (var i=0; i<div.length; i++) {
div[i].insertAdjacentHTML('afterend', div[i].innerHTML);
document.body.removeChild(div[i]);
}
使用Jquery:
function stripTags() {
return $('<p></p>').html(textToEscape).text()
}
这是一个解决@MikeSamuel安全问题的版本:
function strip(html)
{
try {
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = html;
return doc.documentElement.textContent||doc.documentElement.innerText;
} catch(e) {
return "";
}
}
注意,如果HTML标记不是有效的XML,它将返回一个空字符串(也就是,标记必须关闭,属性必须引用)。这并不理想,但确实避免了潜在的安全漏洞问题。
如果不需要有效的XML标记,可以尝试使用:
var doc = document.implementation.createHTMLDocument("");
但出于其他原因,这也不是一个完美的解决方案。
方法1:
function cleanHTML(str){
str.replace(/<(?<=<)(.*?)(?=>)>/g, '<$1>');
}
function uncleanHTML(str){
str.replace(/<(?<=<)(.*?)(?=>)>/g, '<$1>');
}
方法2:
function cleanHTML(str){
str.replace(/</g, '<').replace(/>/g, '>');
}
function uncleanHTML(str){
str.replace(/</g, '<').replace(/>/g, '>');
}
此外,不要忘记,如果用户碰巧发布了一条数学评论(例如:1<2),您不想删除整个评论。浏览器(仅测试了chrome)不将unicode作为html标记运行。如果将所有<替换为<;字符串中的每一个文件,unicode都将显示<为文本,而不运行任何html。我推荐方法2。jquery也能很好地工作$('#element').text();