Home  >  Article  >  Web Front-end  >  How to extract text from HTML tags in text format?

How to extract text from HTML tags in text format?

WBOY
WBOYforward
2023-09-09 22:57:061115browse

How to extract text from HTML tags in text format?

从 HTML 文件中提取文本的行为本质上相当于将网站内容复制并粘贴到记事本上。这听起来可能很简单,但如果您必须从数百万个 HTML 文件(网页)中提取文本,那就不会那么令人愉快了。

让我们深入研究本文,以更好地了解如何从文本格式的 HTML 标记中提取文本。

从 HTML 标记中提取文本

HTML 中的许多元素可用于赋予文本特定的含义。为了获得更多关于从文本格式的 HTML 标记中提取文本的想法,让我们看看以下示例。

示例

在以下示例中,我们运行脚本以从 HTML 标记中提取文本。

<!DOCTYPE html>
<html>
   <body>
      <script>
         function gettext(html){
            var tempDivElement = document.createElement("div");
            tempDivElement.innerHTML = html;
            return tempDivElement.textContent || tempDivElement.innerText || "";
         }
         var sentence= "<div><h1>Welcome to Tutorialspoint</h1></div>";
         document.write(gettext(sentence));
      </script>
   </body>
</html>

当脚本执行时,它将生成由从上述脚本获取的数据组成的输出,并将其显示在网页上。

示例

考虑以下示例,我们正在运行脚本以从 HTML 标记获取文本。

<!DOCTYPE html>
<html>
   <body>
      <script>
         var statement= "<div><h1>TutorialsPoint</h1><p> is the Best E-Learning</p></div>";
         var result = statement.replace(/<[^>]+>/g, '');
         document.write(result)
      </script>
   </body>
</html>

运行上述脚本时,将弹出输出窗口,其中包含通过运行网页上显示的脚本提取的文本。

The above is the detailed content of How to extract text from HTML tags in text format?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete