从文本 JavaScript 中剥离 HTML [英] Strip HTML from Text JavaScript

查看:25
本文介绍了从文本 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 stripHtml(html)
{
   let tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}

注意:正如人们在评论中指出的那样,如果您不控制 HTML 的来源(例如,不要在可能来自用户输入的任何内容上运行它),最好避免这种情况.对于这些场景,您可以仍然让浏览器为您完成工作 - 查看 Saba 关于使用现已广泛使用的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆