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


当前回答

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

其他回答

很多人已经回答了这个问题,但我认为分享我编写的函数可能会有用,该函数可以从字符串中删除HTML标记,但允许您包含一个不希望删除的标记数组。它很短,对我来说一直很好。

function removeTags(string, array){
  return array ? string.split("<").filter(function(val){ return f(array, val); }).map(function(val){ return f(array, val); }).join("") : string.split("<").map(function(d){ return d.split(">").pop(); }).join("");
  function f(array, value){
    return array.map(function(d){ return value.includes(d + ">"); }).indexOf(true) != -1 ? "<" + value : value.split(">")[1];
  }
}

var x = "<span><i>Hello</i> <b>world</b>!</span>";
console.log(removeTags(x)); // Hello world!
console.log(removeTags(x, ["span", "i"])); // <span><i>Hello</i> world!</span>

还可以使用出色的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应用程序,则这在节点和浏览器中都有效。

如果您不想为此创建DOM(可能您不在浏览器上下文中),可以使用striptags npm包。

import striptags from 'striptags'; //ES6 <-- pick one
const striptags = require('striptags'); //ES5 <-- pick one

striptags('<p>An HTML string</p>');

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

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

来自CSS技巧:

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

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