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


当前回答

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'

其他回答

function stripHTML(my_string){
    var charArr   = my_string.split(''),
        resultArr = [],
        htmlZone  = 0,
        quoteZone = 0;
    for( x=0; x < charArr.length; x++ ){
     switch( charArr[x] + htmlZone + quoteZone ){
       case "<00" : htmlZone  = 1;break;
       case ">10" : htmlZone  = 0;resultArr.push(' ');break;
       case '"10' : quoteZone = 1;break;
       case "'10" : quoteZone = 2;break;
       case '"11' : 
       case "'12" : quoteZone = 0;break;
       default    : if(!htmlZone){ resultArr.push(charArr[x]); }
     }
    }
    return resultArr.join('');
}

在新创建的dom元素中说明>内部属性和<img oneror=“javascript”>。

用法:

clean_string = stripHTML("string with <html> in it")

演示:

https://jsfiddle.net/gaby_de_wilde/pqayphzd/

做可怕事情的顶级答案演示:

https://jsfiddle.net/gaby_de_wilde/6f0jymL6/1/

来自CSS技巧:

https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

常量原始字符串=`<div><p>嘿,这是什么东西</p></div>`;conststripedString=originalString.replace(/(<([^>]+)>)/gi,“”);console.log(strippedString);

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

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

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

还可以使用出色的htmlparser2纯JSHTML解析器。这里是一个工作演示:

var htmlparser = require('htmlparser2');

var body = '<p><div>This is </div>a <span>simple </span> <img src="test"></img>example.</p>';

var result = [];

var parser = new htmlparser.Parser({
    ontext: function(text){
        result.push(text);
    }
}, {decodeEntities: true});

parser.write(body);
parser.end();

result.join('');

输出将是这是一个简单的示例。

请在此处查看实际操作:https://tonicdev.com/jfahrenkrug/extract-text-from-html

如果您使用类似webpack的工具打包web应用程序,则这在节点和浏览器中都有效。