有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?


当前回答

用jQuery剥离html的一种更安全的方法是,首先使用jQuery.parseHTML创建DOM,忽略任何脚本,然后让jQuery构建元素,然后仅检索文本。

function stripHtml(unsafe) {
    return $($.parseHTML(unsafe)).text();
}

可以安全地从以下位置剥离html:

<img src="unknown.gif" onerror="console.log('running injections');">

以及其他漏洞。

nJoy!

其他回答

如果你在浏览器中运行,那么最简单的方法就是让浏览器为你做。。。

function stripHtml(html)
{
   let tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}

注意:正如人们在评论中所指出的,如果您不控制HTML的源代码(例如,不要在可能来自用户输入的任何内容上运行此代码),最好避免这种情况。对于这些场景,您仍然可以让浏览器为您完成工作-请参阅Saba关于使用现在广泛可用的DOMParser的回答。

下面的代码允许您保留一些html标记,同时剥离所有其他标记

function strip_tags(input, allowed) {

  allowed = (((allowed || '') + '')
    .toLowerCase()
    .match(/<[a-z][a-z0-9]*>/g) || [])
    .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)

  var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
      commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;

  return input.replace(commentsAndPhpTags, '')
      .replace(tags, function($0, $1) {
          return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
      });
}

对公认答案的改进。

function strip(html)
{
   var tmp = document.implementation.createHTMLDocument("New").body;
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}

这样一来,像这样运行的东西不会造成任何伤害:

strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")

Firefox、Chromium和Explorer 9+是安全的。歌剧院普雷斯托仍然很脆弱。字符串中提到的图像也不会在Chromium和Firefox中保存http请求。

myString.replace(/<[^>]*>?/gm, '');
var text = html.replace(/<\/?("[^"]*"|'[^']*'|[^>])*(>|$)/g, "");

这是一个正则表达式版本,对格式错误的HTML更具弹性,例如:

未闭合的标记

某些文本<img

标记属性内的“<”,“>”

某些文本<img alt=“x>y”>

换行符

一些<ahref=“http://google.com">

代码

var html = '<br>This <img alt="a>b" \r\n src="a_b.gif" />is > \nmy<>< > <a>"text"</a'
var text = html.replace(/<\/?("[^"]*"|'[^']*'|[^>])*(>|$)/g, "");