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


当前回答

下面的代码允许您保留一些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_tags(str)
{
   if ((str===null) || (str===''))
       return false;
  else
   str = str.toString();
  return str.replace(/<[^>]*>/g, '');
}

对公认答案的改进。

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请求。

作为jQuery方法的扩展,如果字符串可能不包含HTML(例如,如果您试图从表单字段中删除HTML)

jQuery(html).text();

如果没有HTML,将返回空字符串

Use:

jQuery('<p>' + html + '</p>').text();

相反

更新:正如评论中所指出的,在某些情况下,如果攻击者可能影响html的值,则此解决方案将执行html中包含的javascript,请使用不同的解决方案。

一个非常好的库是净化html,它是一个纯JavaScript函数,可以在任何环境中使用。

我的案例是React Native,我需要从给定文本中删除所有HTML标记。所以我创建了这个包装函数:

import sanitizer from 'sanitize-html';

const textSanitizer = (textWithHTML: string): string =>
  sanitizer(textWithHTML, {
    allowedTags: [],
  });

export default textSanitizer;

现在,通过使用textSanitizer,我可以获得纯文本内容。

简单的2行jquery去掉html。

 var content = "<p>checking the html source&nbsp;</p><p>&nbsp;
  </p><p>with&nbsp;</p><p>all</p><p>the html&nbsp;</p><p>content</p>";

 var text = $(content).text();//It gets you the plain text
 console.log(text);//check the data in your console

 cj("#text_area_id").val(text);//set your content to text area using text_area_id