HTML Minifier for Swift
Free online html minifier with Swift code examples
Working with html minifier in Swift? Our free online html minifier helps Swift developers format, validate, and process data instantly. Below you will find Swift code examples using Custom regex-based minifier so you can achieve the same result programmatically in your own projects.
Try the HTML Minifier Online
Use our free HTML Minifier directly in your browser — no setup required.
Open HTML MinifierSwift Code Example
import Foundation
func minifyHTML(_ html: String) -> String {
var result = html
// Remove HTML comments
result = result.replacingOccurrences(
of: "<!--[\\s\\S]*?-->", with: "", options: .regularExpression)
// Collapse whitespace between tags
result = result.replacingOccurrences(
of: ">\\s+<", with: "><", options: .regularExpression)
// Collapse remaining whitespace
result = result.replacingOccurrences(
of: "\\s+", with: " ", options: .regularExpression)
return result.trimmingCharacters(in: .whitespaces)
}
let html = """
<!DOCTYPE html>
<html>
<head><title>Hello</title></head>
<body>
<!-- comment -->
<h1>Hello World</h1>
</body>
</html>
"""
print(minifyHTML(html))Quick Setup
Library: Custom regex-based minifier
// No external dependency neededSwift Tips & Best Practices
- Regex-based minification works for basic HTML
- Be careful not to collapse whitespace inside pre or code tags
- For production, use a build tool like Webpack or esbuild