从文本JavaScript中去除HTML [英] Strip HTML from Text JavaScript
本文介绍了从文本JavaScript中去除HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种简单的方法在JavaScript中取出一串html并去掉html?
Is there an easy way to take a string of html in JavaScript and strip out the html?
推荐答案
If you're running in a browser, then the easiest way is just to let the browser do it for you...
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
注意:正如人们在评论中指出的那样,如果您不要控制HTML的源代码(例如,不要在任何可能来自用户输入的东西上运行此代码)。对于这些情况,您仍然可以让浏览器为您完成工作 - 请参阅萨巴关于使用现在广泛使用的DOMParser的答案。
Note: as folks have noted in the comments, this is best avoided if you don't control the source of the HTML (for example, don't run this on anything that could've come from user input). For those scenarios, you can still let the browser do the work for you - see Saba's answer on using the now widely-available DOMParser.
这篇关于从文本JavaScript中去除HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文