Skip to content

Instantly share code, notes, and snippets.

@johnatandias
Created April 26, 2020 14:19
Show Gist options
  • Save johnatandias/a721b9a29d2e28fb5b5321a06deb5819 to your computer and use it in GitHub Desktop.
Save johnatandias/a721b9a29d2e28fb5b5321a06deb5819 to your computer and use it in GitHub Desktop.
Minify HTML files with Javascript
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Document</title>
</head>
<body>
<div>
<span>Hello</span><i>World</i>
</div>
</body>
</html>
`;
const minify = html => html
.replace(/\>[\r\n ]+\</g, "><")
.replace(/(<.*?>)|\s+/g, (m, $1) => $1 ? $1 : ' ')
.trim();
console.log(html);
console.log(minify(html));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment