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


当前回答

对于转义字符,也可以使用模式匹配:

myString.replace(/((&lt)|(<)(?:.|\n)*?(&gt)|(>))/gm, '');

其他回答

这应该可以在任何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, '');
    (function($){
        $.html2text = function(html) {
            if($('#scratch_pad').length === 0) {
                $('<div id="lh_scratch"></div>').appendTo('body');  
            }
            return $('#scratch_pad').html(html).text();
        };

    })(jQuery);

将其定义为jquery插件,并按如下方式使用:

$.html2text(htmlContent);
const strip=(text) =>{
    return (new DOMParser()?.parseFromString(text,"text/html"))
    ?.body?.textContent
}

const value=document.getElementById("idOfEl").value

const cleanText=strip(value)

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

jQuery(html).text();

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

Use:

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

相反

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

要获得更简单的解决方案,请尝试此=>https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");