首页 > 解决方案 > 使用 REGEX 在节点 js 中提取 HTML 文档的文本

问题描述

我正在编写一个代码来从 HTML 代码的标签中提取所有纯文本内容。我知道它可以使用文档元素来完成。但是我只需要使用 REGEX 来执行此操作我已经编写了以下代码,但是它有一些我无法弄清楚如何解决它的错误。

function htmlToText(html) {
      return html.
        replace(/(.|\n)*<body.*>/, ''). //remove up till body
        replace(/<\/body(.|\n)*/, ''). //remove from </body
        replace(/<.+\>/, ''). //remove tags
        replace(/^\s\n*$/gm, '');  //remove empty lines
    }

这是它的解决方案

function htmlToText(html) {
          return html.
            replace(/(.|\n)*<body.*>/, ''). //remove up till body
            replace(/<\/body(.|\n)*/g, ''). //remove from </body
            replace(/<.+\>/g, ''). //remove tags
            replace(/^\s\n*$/gm, '');  //remove empty lines
        }

标签: javascripthtmlnode.jsregex

解决方案


不用想太多,你可以document.body.innerText

A Sample Document
Some strong and emphasized text

JSFiddle 示例


推荐阅读