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


当前回答

使用Jquery:

function stripTags() {
    return $('<p></p>').html(textToEscape).text()
}

其他回答

这应该可以在任何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, '');

正如其他人所建议的,我建议尽可能使用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, '');

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

使用jQuery,您可以使用

$('#elementID').text()

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

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

大多数情况下,接受的答案都很好,但是在IE中,如果html字符串为空,则会得到“null”(而不是“”)。固定的:

function strip(html)
{
   if (html == null) return "";
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}