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


当前回答

另一个公认不如nickf或Shog9优雅的解决方案是从<body>标记开始递归遍历DOM并附加每个文本节点。

var bodyContent = document.getElementsByTagName('body')[0];
var result = appendTextNodes(bodyContent);

function appendTextNodes(element) {
    var text = '';

    // Loop through the childNodes of the passed in element
    for (var i = 0, len = element.childNodes.length; i < len; i++) {
        // Get a reference to the current child
        var node = element.childNodes[i];
        // Append the node's value if it's a text node
        if (node.nodeType == 3) {
            text += node.nodeValue;
        }
        // Recurse through the node's children, if there are any
        if (node.childNodes.length > 0) {
            appendTextNodes(node);
        }
    }
    // Return the final result
    return text;
}

其他回答

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

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

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

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

以及其他漏洞。

nJoy!

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, "");

您可以使用以下正则表达式去掉所有html标记:/<(.|\n)*?>/克

例子:

let str = "<font class=\"ClsName\">int[0]</font><font class=\"StrLit\">()</font>";
console.log(str.replace(/<(.|\n)*?>/g, ''));

输出:

int[0]()

这是一个解决@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("");

但出于其他原因,这也不是一个完美的解决方案。

下面的代码允许您保留一些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 : '';
      });
}