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


当前回答

正如其他人所建议的,我建议尽可能使用DOMParser。

然而,如果您恰好在Node/JS Lambda内部工作,或者DOMParser不可用,我会使用下面的正则表达式来匹配前面的回答/评论中提到的大多数场景。它与$gt;不匹配;和$lt;正如其他一些人可能担心的那样,但应该捕捉到几乎任何其他场景。

const dangerousText = '?';
const htmlTagRegex = /<\/?([a-zA-Z]\s?)*?([a-zA-Z]+?=\s?".*")*?([\s/]*?)>/gi;
const sanitizedText = dangerousText.replace(htmlTagRegex, '');

这可能很容易简化,但它应该适用于大多数情况。希望这对某人有所帮助。

其他回答

我想分享一下Shog9批准答案的编辑版本。


正如Mike Samuel在评论中指出的那样,该函数可以执行内联javascript代码。但Shog9说“让浏览器为你做……”是对的

所以…这里是我的编辑版本,使用DOMParser:

function strip(html){
   let doc = new DOMParser().parseFromString(html, 'text/html');
   return doc.body.textContent || "";
}

这里是测试内联javascript的代码:

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

此外,它不会在解析时请求资源(如图像)

strip("Just text <img src='https://assets.rbl.ms/4155638/980x.jpg'>")

最简单的方法:

jQuery(html).text();

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

这应该可以在任何Javascript环境(包括NodeJS)上完成工作。

    const text = `
    <html lang="en">
      <head>
        <style type="text/css">*{color:red}</style>
        <script>alert('hello')</script>
      </head>
      <body><b>This is some text</b><br/><body>
    </html>`;
    
    // Remove style tags and content
    text.replace(/<style[^>]*>.*<\/style>/gm, '')
        // Remove script tags and content
        .replace(/<script[^>]*>.*<\/script>/gm, '')
        // Remove all opening, closing and orphan HTML tags
        .replace(/<[^>]+>/gm, '')
        // Remove leading spaces and repeated CR/LF
        .replace(/([\r\n]+ +)+/gm, '');