How to Minify HTML with JavaScript?

Estimated read time 2 min read

Minifying HTML means removing all unnecessary white spaces, line breaks, and comments to reduce the size of the HTML file, which can improve the loading speed of a website.

Here’s an example of a JavaScript function that minifies an HTML string:

function minifyHTML(html) {
  return html.replace(/(\r\n|\n|\r)/gm, '')  // remove line breaks
    .replace(/\s+/g, ' ') // collapse multiple white spaces into a single space
    .replace(/<!--(?!\[).*?-->/g, ''); // remove HTML comments

You can use this function to minify an HTML string by passing it as an argument:

let html = `<html>
    <h1>Hello, World!</h1>

let minifiedHTML = minifyHTML(html);

This will output the following minified HTML:

<html><head><title>Example</title></head><body><h1>Hello, World!</h1></body></html>

Note that this is a very simple example and may not cover all cases. If you need to minify your HTML in a production environment, you may want to consider using a more robust library or tool designed specifically for this task.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply