HTML Formatter `;
// Initialize with sample HTML
inputEl.value = sampleHTML;
formatHTML();
// Event Listeners
formatBtn.addEventListener('click', formatHTML);
minifyBtn.addEventListener('click', minifyHTML);
copyBtn.addEventListener('click', copyOutput);
clearBtn.addEventListener('click', clearAll);
inputEl.addEventListener('input', updateInputStats);
// Format HTML with proper indentation
function formatHTML() {
const input = inputEl.value.trim();
if (!input) {
showNotification('Please enter some HTML code', 'error');
return;
}
try {
let formatted = '';
let indentLevel = 0;
const indentStr = ' '; // 2 spaces for indentation
// Process the HTML line by line
const lines = input.split('\n');
for (let line of lines) {
// Trim the line
const trimmed = line.trim();
if (!trimmed) continue;
// Handle closing tags that reduce indentation
if (trimmed.startsWith('') ||
trimmed.endsWith('/>') ||
trimmed.includes('')) {
indentLevel = Math.max(0, indentLevel - 1);
}
// Add current line with proper indentation
formatted += indentStr.repeat(indentLevel) + trimmed + '\n';
// Handle opening tags that increase indentation
if (trimmed.startsWith('<') && !trimmed.startsWith('') &&
!trimmed.includes('/>') && !trimmed.includes('') &&
!trimmed.endsWith('>') || trimmed.endsWith('>') &&
!trimmed.includes('/>') && !trimmed.startsWith('')) {
indentLevel += 1;
}
}
// Apply syntax highlighting
formatted = applySyntaxHighlighting(formatted);
// Update output
outputEl.innerHTML = formatted;
// Update stats
updateStats(input, formatted);
showNotification('HTML formatted successfully!');
} catch (error) {
showNotification('Error formatting HTML. Please check your code.', 'error');
console.error(error);
}
}
// Minify HTML by removing extra whitespace
function minifyHTML() {
const input = inputEl.value.trim();
if (!input) {
showNotification('Please enter some HTML code', 'error');
return;
}
try {
// Simple minification (remove whitespace between tags)
let minified = input
.replace(/\s+/g, ' ') // Replace multiple spaces with single space
.replace(/>\s+<') // Remove spaces between tags
.trim();
// Apply syntax highlighting (minified version will be on one line)
minified = applySyntaxHighlighting(minified);
// Update output
outputEl.innerHTML = minified;
// Update stats
updateStats(input, minified);
showNotification('HTML minified successfully!');
} catch (error) {
showNotification('Error minifying HTML', 'error');
console.error(error);
}
}
// Apply syntax highlighting to HTML
function applySyntaxHighlighting(html) {
return html
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/\n/g, '
')
.replace(/("([^"]*)")/g, '
$1')
.replace(/(<\/?[a-zA-Z][^>]*>)/g, '
$1')
.replace(/([a-zA-Z-]+)=/g, '
$1=')
.replace(/<!--[\s\S]*?-->/g, '');
}
// Copy output to clipboard
function copyOutput() {
const textToCopy = outputEl.textContent || outputEl.innerText;
if (!textToCopy.trim()) {
showNotification('No output to copy', 'error');
return;
}
// Use the Clipboard API
navigator.clipboard.writeText(textToCopy)
.then(() => {
showNotification('Output copied to clipboard!');
// Temporarily change button text
const originalHTML = copyBtn.innerHTML;
copyBtn.innerHTML = '
Copied!';
setTimeout(() => {
copyBtn.innerHTML = originalHTML;
}, 2000);
})
.catch(err => {
console.error('Failed to copy: ', err);
showNotification('Failed to copy to clipboard', 'error');
});
}
// Clear both input and output
function clearAll() {
inputEl.value = '';
outputEl.innerHTML = '';
updateStats('', '');
inputEl.focus();
showNotification('All fields cleared');
}
// Update statistics
function updateStats(input, output) {
const inputLines = input ? input.split('\n').length : 0;
const outputLines = output ? output.split('\n').length : 0;
const inputChars = input ? input.length : 0;
const outputChars = output ? output.replace(/<[^>]*>/g, '').length : 0;
inputLinesEl.textContent = inputLines;
outputLinesEl.textContent = outputLines;
inputCharsEl.textContent = inputChars;
outputCharsEl.textContent = outputChars;
}
// Update input stats in real-time
function updateInputStats() {
const input = inputEl.value;
const inputLines = input ? input.split('\n').length : 0;
const inputChars = input ? input.length : 0;
inputLinesEl.textContent = inputLines;
inputCharsEl.textContent = inputChars;
}
// Show notification
function showNotification(message, type = 'success') {
notificationEl.textContent = message;
notificationEl.className = 'notification';
if (type === 'error') {
notificationEl.classList.add('error');
}
notificationEl.classList.add('show');
// Hide after 3 seconds
setTimeout(() => {
notificationEl.classList.remove('show');
}, 3000);
}
// Initialize stats on page load
updateInputStats();