要实现 HTML 压缩,可以使用 JavaScript 中的正则表达式来去除 HTML 中的空格和注释。以下是一个简单的 HTML 压缩函数:

function compressHTML(html) { // 去除注释 html = html.replace(//g, ""); // 去除多余空白 html = html.replace(/\s+/g, " "); // 去除标签之间空格 html = html.replace(/>\s+<"); return html.trim();}

该函数首先使用正则表达式去除 HTML 中的注释。然后,它使用另一个正则表达式去除 HTML 中的多余空格。最后,它使用另一个正则表达式去除标签之间的空格。

为了测试该函数,您可以创建一个 HTML 文件,并在其中添加一些冗余的空格和注释。例如:

Welcome to my website!

This is some text.

然后,您可以在Node.JS中使用以下代码将 HTML 文件加载为字符串并压缩它:

// 加载 HTML 文件const fs = require("fs");const html = fs.readFileSync("index.html", "utf8");// 压缩 HTMLconst compressedHtml = compressHTML(html);console.log(compressedHtml);

输出是一个压缩后的 HTML 字符串,其中不包含注释或冗余空格。

或者直接在IE中测试,代码如下:

function compressHTML(html) { // 去除注释 html = html.replace(//g, ""); // 去除多余空白 html = html.replace(/\s+/g, " "); // 去除标签之间空格 html = html.replace(/>\s+<"); return html.trim();}var html =` `;console.log(compressHTML(html));

Welcome to my website!

This is some text.

运行效果: