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


当前回答

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

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

其他回答

const getTextFromHtml = (t) =>
  t
    ?.split('>')
    ?.map((i) => i.split('<')[0])
    .filter((i) => !i.includes('=') && i.trim())
    .join('');

const test = '<p>This <strong>one</strong> <em>time</em>,</p><br /><blockquote>I went to</blockquote><ul><li>band <a href="https://workingclasshistory.com" rel="noopener noreferrer" target="_blank">camp</a>…</li></ul><p>I edited this as a reviewer just to double check</p>'

getTextFromHtml(test)
  // 'This onetime,I went toband camp…I edited this as a reviewer just to double check'

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

使用jQuery,您可以使用

$('#elementID').text()

这个包非常适合剥离HTML:https://www.npmjs.com/package/string-strip-html

它可以在浏览器和服务器(例如Node.js)上工作。