Real-Time HTML Encoding & Decoding

Characters: 0
Characters: 0
Conversion Statistics
0
Encoded Characters
0
Decoded Characters
0ms
Conversion Time
0
Total Conversions

Advanced Features

Encoding Type

Conversion History

Time Operation Input Preview Output Preview Actions
No conversion history yet. Perform your first conversion!

How to Use the HTML Encoder/Decoder Tool: A Complete Guide

This comprehensive guide explains how to effectively use our HTML Encoder/Decoder tool for web development and security purposes. HTML encoding is essential for preventing Cross-Site Scripting (XSS) attacks and ensuring special characters display correctly in web applications[citation:1].

What is HTML Encoding?

HTML encoding converts special characters into HTML entities that browsers can safely display. For example, the less-than symbol (<) becomes &lt; and the ampersand (&) becomes &amp;. This prevents browsers from interpreting these characters as HTML tags or script elements[citation:6].

Key Features and How to Use Them

1. Basic Encoding & Decoding

Enter your text in the Input Text area and click Encode HTML to convert special characters to entities. Use Decode HTML to convert entities back to regular text. The conversion happens in real-time with statistics displayed instantly.

2. URL Encoding/Decoding

Use the URL Encode and URL Decode features to safely include special characters in URLs. This is essential for creating query strings and handling user input in web addresses.

3. Base64 Conversion

The Base64 Encode and Decode features allow you to convert binary data to ASCII text format and back. This is useful for data transmission and embedding small files in web pages.

4. XSS Detection

Our tool includes an XSS Detection feature that scans your text for potential Cross-Site Scripting vulnerabilities. This helps developers identify and fix security issues before deploying code to production environments[citation:1].

5. Text Comparison

The Compare Texts feature highlights differences between your input and output, making it easy to see exactly what changed during encoding or decoding.

Real-World Applications

  • Web Form Security: Encode user input before displaying it to prevent XSS attacks
  • Data Transmission: Safely transmit special characters via URLs or APIs
  • Content Management: Ensure user-generated content displays correctly without breaking page layout
  • Code Development: Test encoding/decoding functions during development
  • Security Auditing: Check existing code for potential vulnerabilities

Pro Tips for Maximum Effectiveness

  1. Enable Auto-Convert to see changes in real-time as you type
  2. Use the Conversion History to track your work and revert to previous versions
  3. Try different Encoding Types (Hexadecimal, Decimal, Named Entities) for specific use cases
  4. Export your history for documentation or further analysis
  5. Use the Swap feature to quickly move converted text back to the input area for further processing

By incorporating this tool into your development workflow, you can enhance application security, ensure proper text rendering, and save time on manual encoding tasks. Remember that in today's digital landscape, real-time security tools are not just an advantage—they're a necessity for protecting your web applications[citation:1].

Quick Tips
  • Always encode user input before displaying it on your website
  • Use URL encoding for query parameters
  • Test for XSS vulnerabilities during development
  • Preserve formatting when copying encoded text
  • Bookmark this tool for quick access
Security Best Practices

Input Validation: Always validate and sanitize user input on both client and server sides.

Output Encoding: Encode data right before rendering it in the browser context where it will be used.

Content Security Policy: Implement CSP headers to mitigate XSS risks.

Regular Testing: Use this tool to regularly test your applications for encoding issues.

& "Special'Chars"`; updateCharCounts(); // Load saved settings const autoConvert = localStorage.getItem('autoConvert') === 'true'; chkAutoConvert.checked = autoConvert; // If auto-convert is enabled, perform initial conversion if (autoConvert) { performEncoding(); } }); // Update character counts function updateCharCounts() { const inputCount = inputText.value.length; const outputCount = outputText.value.length; inputCharCount.textContent = `Characters: ${inputCount}`; outputCharCount.textContent = `Characters: ${outputCount}`; } // Update statistics display function updateStats() { statEncodedChars.textContent = encodedChars; statDecodedChars.textContent = decodedChars; statTotalConversions.textContent = totalConversions; // Save stats to localStorage localStorage.setItem('encodedChars', encodedChars); localStorage.setItem('decodedChars', decodedChars); localStorage.setItem('totalConversions', totalConversions); } // HTML Encoding Functions function encodeHTML(text, type = 'html') { const preserveSpaces = chkPreserveSpaces.checked; // Create a temporary div to handle HTML entity conversion const tempDiv = document.createElement('div'); tempDiv.textContent = text; let encoded = tempDiv.innerHTML; // Additional encoding based on type if (type === 'hex') { // Convert to hexadecimal entities encoded = encoded.replace(/[^\w\s]/g, function(c) { return '&#x' + c.charCodeAt(0).toString(16) + ';'; }); } else if (type === 'decimal') { // Convert to decimal entities encoded = encoded.replace(/[^\w\s]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; }); } else if (type === 'named') { // Use named entities for common characters const namedEntities = { '"': '"', '&': '&', "'": ''', '<': '<', '>': '>', '©': '©', '®': '®', '€': '€', '£': '£', '¥': '¥' }; encoded = encoded.replace(/["&'<>©®€£¥]/g, function(c) { return namedEntities[c] || '&#' + c.charCodeAt(0) + ';'; }); } // Handle spaces if preserveSpaces is false if (!preserveSpaces) { encoded = encoded.replace(/\s+/g, ' ').trim(); } return encoded; } function decodeHTML(text) { const tempDiv = document.createElement('div'); tempDiv.innerHTML = text; return tempDiv.textContent; } // URL Encoding Functions function encodeURL(text) { return encodeURIComponent(text); } function decodeURL(text) { try { return decodeURIComponent(text); } catch (e) { return "Error: Invalid URL encoding"; } } // Base64 Functions function encodeBase64(text) { return btoa(unescape(encodeURIComponent(text))); } function decodeBase64(text) { try { return decodeURIComponent(escape(atob(text))); } catch (e) { return "Error: Invalid Base64 string"; } } // JavaScript Escape Functions function escapeJS(text) { return text.replace(/[\\"']/g, '\\$&').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t'); } function unescapeJS(text) { return text.replace(/\\([\\'"nrt])/g, function(match, char) { const escapes = {n: '\n', r: '\r', t: '\t', '\\': '\\', '"': '"', "'": "'"}; return escapes[char] || char; }); } // Strip HTML Tags function stripTags(text) { return text.replace(/<[^>]*>/g, ''); } // Minify HTML function minifyHTML(text) { return text.replace(/\s+/g, ' ').replace(/>\s+<').trim(); } // XSS Detection function detectXSS(text) { const xssPatterns = [ /]*>([\s\S]*?)<\/script>/gi, /javascript:/gi, /on\w+\s*=/gi, /<\s*iframe/gi, /<\s*form/gi, /<\s*meta/gi, /<\s*object/gi, /<\s*embed/gi, /<\s*applet/gi, /<\s*link/gi, /expression\s*\(/gi, /vbscript:/gi ]; let detected = []; xssPatterns.forEach((pattern, index) => { const matches = text.match(pattern); if (matches) { detected.push({ pattern: pattern.toString(), matches: matches.length }); } }); return detected; } // Perform encoding operation function performEncoding() { const startTime = performance.now(); const input = inputText.value; const encodingType = selEncodingType.value; if (!input.trim()) { outputText.value = ""; updateCharCounts(); return; } const encoded = encodeHTML(input, encodingType); outputText.value = encoded; // Update stats const endTime = performance.now(); const conversionTime = Math.round(endTime - startTime); statConversionTime.textContent = `${conversionTime}ms`; encodedChars += encoded.length; totalConversions++; updateStats(); // Add to history addToHistory('Encode HTML', input, encoded); updateCharCounts(); } // Perform decoding operation function performDecoding() { const startTime = performance.now(); const input = inputText.value; if (!input.trim()) { outputText.value = ""; updateCharCounts(); return; } const decoded = decodeHTML(input); outputText.value = decoded; // Update stats const endTime = performance.now(); const conversionTime = Math.round(endTime - startTime); statConversionTime.textContent = `${conversionTime}ms`; decodedChars += decoded.length; totalConversions++; updateStats(); // Add to history addToHistory('Decode HTML', input, decoded); updateCharCounts(); } // Add conversion to history function addToHistory(operation, input, output) { const historyItem = { id: Date.now(), timestamp: new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}), date: new Date().toLocaleDateString(), operation: operation, input: input.length > 50 ? input.substring(0, 47) + '...' : input, output: output.length > 50 ? output.substring(0, 47) + '...' : output, fullInput: input, fullOutput: output }; conversionHistory.unshift(historyItem); // Keep only last 20 items if (conversionHistory.length > 20) { conversionHistory = conversionHistory.slice(0, 20); } // Save to localStorage localStorage.setItem('htmlEncoderHistory', JSON.stringify(conversionHistory)); // Update UI renderHistory(); } // Render history table function renderHistory() { if (conversionHistory.length === 0) { historyEmptyRow.style.display = ''; return; } historyEmptyRow.style.display = 'none'; // Clear current rows (except empty row) const rows = historyTableBody.querySelectorAll('tr:not(#historyEmptyRow)'); rows.forEach(row => row.remove()); // Add history rows conversionHistory.forEach(item => { const row = document.createElement('tr'); row.innerHTML = ` ${item.timestamp} ${item.operation} ${escapeHTML(item.input)} ${escapeHTML(item.output)} `; historyTableBody.appendChild(row); }); // Add event listeners to restore buttons document.querySelectorAll('.btn-restore').forEach(btn => { btn.addEventListener('click', function() { const id = parseInt(this.getAttribute('data-id')); const item = conversionHistory.find(item => item.id === id); if (item) { inputText.value = item.fullInput; outputText.value = item.fullOutput; updateCharCounts(); Swal.fire({ title: 'Restored!', text: 'Previous conversion has been restored.', icon: 'success', timer: 1500, showConfirmButton: false, customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } }); }); } // Helper function to escape HTML for display function escapeHTML(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } // Event Listeners // Main buttons btnEncode.addEventListener('click', performEncoding); btnDecode.addEventListener('click', performDecoding); btnCopyOutput.addEventListener('click', function() { if (!outputText.value.trim()) { Swal.fire({ title: 'No Output', text: 'There is no output text to copy.', icon: 'warning', customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); return; } navigator.clipboard.writeText(outputText.value).then(() => { Swal.fire({ title: 'Copied!', text: 'Output text copied to clipboard.', icon: 'success', timer: 1500, showConfirmButton: false, customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }); }); btnClearInput.addEventListener('click', function() { inputText.value = ''; updateCharCounts(); if (chkAutoConvert.checked) { outputText.value = ''; updateCharCounts(); } }); btnClearOutput.addEventListener('click', function() { outputText.value = ''; updateCharCounts(); }); btnSwapText.addEventListener('click', function() { const temp = inputText.value; inputText.value = outputText.value; outputText.value = temp; updateCharCounts(); if (chkAutoConvert.checked) { performEncoding(); } }); btnResetAll.addEventListener('click', function() { Swal.fire({ title: 'Reset All?', text: 'This will clear all input, output, and history. This action cannot be undone.', icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, reset all', cancelButtonText: 'Cancel', customClass: { confirmButton: 'btn btn-danger me-2', cancelButton: 'btn btn-secondary' }, buttonsStyling: false }).then((result) => { if (result.isConfirmed) { inputText.value = ''; outputText.value = ''; conversionHistory = []; totalConversions = 0; encodedChars = 0; decodedChars = 0; localStorage.removeItem('htmlEncoderHistory'); localStorage.removeItem('totalConversions'); localStorage.removeItem('encodedChars'); localStorage.removeItem('decodedChars'); updateCharCounts(); updateStats(); renderHistory(); Swal.fire({ title: 'Reset Complete!', text: 'All data has been cleared.', icon: 'success', timer: 1500, showConfirmButton: false, customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } }); }); btnQuickDemo.addEventListener('click', function() { inputText.value = `Try our tool with this example:\n\n1. \n2. User input: \n3. Special chars: > < & " '\n4. URL: https://example.com?q=search&sort=desc`; updateCharCounts(); if (chkAutoConvert.checked) { performEncoding(); } Swal.fire({ title: 'Demo Loaded!', text: 'Try encoding this example text to see how the tool works.', icon: 'info', timer: 2000, showConfirmButton: false, customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }); // History buttons btnClearHistory.addEventListener('click', function() { Swal.fire({ title: 'Clear History?', text: 'This will remove all conversion history. This action cannot be undone.', icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, clear history', cancelButtonText: 'Cancel', customClass: { confirmButton: 'btn btn-danger me-2', cancelButton: 'btn btn-secondary' }, buttonsStyling: false }).then((result) => { if (result.isConfirmed) { conversionHistory = []; localStorage.removeItem('htmlEncoderHistory'); renderHistory(); Swal.fire({ title: 'History Cleared!', text: 'All conversion history has been removed.', icon: 'success', timer: 1500, showConfirmButton: false, customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } }); }); btnExportHistory.addEventListener('click', function() { if (conversionHistory.length === 0) { Swal.fire({ title: 'No History', text: 'There is no conversion history to export.', icon: 'warning', customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); return; } // Create CSV content let csv = 'Timestamp,Date,Operation,Input,Output\n'; conversionHistory.forEach(item => { const input = item.fullInput.replace(/"/g, '""'); const output = item.fullOutput.replace(/"/g, '""'); csv += `"${item.timestamp}","${item.date}","${item.operation}","${input}","${output}"\n`; }); // Create download link const blob = new Blob([csv], { type: 'text/csv' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `html-encoder-history-${new Date().toISOString().slice(0, 10)}.csv`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); Swal.fire({ title: 'Exported!', text: 'Conversion history has been exported as CSV.', icon: 'success', timer: 1500, showConfirmButton: false, customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); }); // Advanced Features btnEncodeURL.addEventListener('click', function() { const input = inputText.value; if (!input.trim()) return; outputText.value = encodeURL(input); updateCharCounts(); addToHistory('URL Encode', input, outputText.value); }); btnDecodeURL.addEventListener('click', function() { const input = inputText.value; if (!input.trim()) return; outputText.value = decodeURL(input); updateCharCounts(); addToHistory('URL Decode', input, outputText.value); }); btnEncodeBase64.addEventListener('click', function() { const input = inputText.value; if (!input.trim()) return; outputText.value = encodeBase64(input); updateCharCounts(); addToHistory('Base64 Encode', input, outputText.value); }); btnDecodeBase64.addEventListener('click', function() { const input = inputText.value; if (!input.trim()) return; outputText.value = decodeBase64(input); updateCharCounts(); addToHistory('Base64 Decode', input, outputText.value); }); btnEscapeJS.addEventListener('click', function() { const input = inputText.value; if (!input.trim()) return; outputText.value = escapeJS(input); updateCharCounts(); addToHistory('Escape JS', input, outputText.value); }); btnUnescapeJS.addEventListener('click', function() { const input = inputText.value; if (!input.trim()) return; outputText.value = unescapeJS(input); updateCharCounts(); addToHistory('Unescape JS', input, outputText.value); }); btnStripTags.addEventListener('click', function() { const input = inputText.value; if (!input.trim()) return; outputText.value = stripTags(input); updateCharCounts(); addToHistory('Strip Tags', input, outputText.value); }); btnMinifyHTML.addEventListener('click', function() { const input = inputText.value; if (!input.trim()) return; outputText.value = minifyHTML(input); updateCharCounts(); addToHistory('Minify HTML', input, outputText.value); }); btnXSSDetect.addEventListener('click', function() { const input = inputText.value; if (!input.trim()) { Swal.fire({ title: 'No Input', text: 'Please enter text to analyze for XSS vulnerabilities.', icon: 'warning', customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); return; } const detected = detectXSS(input); if (detected.length === 0) { Swal.fire({ title: 'No XSS Detected', html: '

No Cross-Site Scripting vulnerabilities detected in the input text.

', customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); } else { let html = '
'; html += '

Potential XSS vulnerabilities detected:

Consider encoding this text before using it in HTML context.

'; Swal.fire({ title: 'XSS Vulnerabilities Found!', html: html, icon: 'warning', width: '600px', customClass: { confirmButton: 'btn btn-danger' }, buttonsStyling: false }); } addToHistory('XSS Detect', input, detected.length > 0 ? 'XSS detected' : 'No XSS'); }); btnTextDiff.addEventListener('click', function() { const input = inputText.value; const output = outputText.value; if (!input.trim() || !output.trim()) { Swal.fire({ title: 'Comparison Error', text: 'Both input and output must contain text to compare.', icon: 'warning', customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); return; } // Simple text comparison let diffHtml = '
'; diffHtml += '
Input vs Output Comparison
'; diffHtml += '

Input Length: ' + input.length + ' characters

'; diffHtml += '

Output Length: ' + output.length + ' characters

'; if (input === output) { diffHtml += '
Input and output are identical.
'; } else { diffHtml += '
Input and output differ.
'; // Show first difference const minLength = Math.min(input.length, output.length); let firstDiffIndex = -1; for (let i = 0; i < minLength; i++) { if (input[i] !== output[i]) { firstDiffIndex = i; break; } } if (firstDiffIndex !== -1) { const contextStart = Math.max(0, firstDiffIndex - 10); const contextEnd = Math.min(minLength, firstDiffIndex + 10); diffHtml += '

First difference at position ' + firstDiffIndex + ':

'; diffHtml += '

Input context: ...' + escapeHTML(input.substring(contextStart, contextEnd)) + '...

'; diffHtml += '

Output context: ...' + escapeHTML(output.substring(contextStart, contextEnd)) + '...

'; } } diffHtml += '
'; Swal.fire({ title: 'Text Comparison', html: diffHtml, width: '700px', customClass: { confirmButton: 'btn btn-primary' }, buttonsStyling: false }); addToHistory('Compare Texts', input, 'Comparison performed'); }); // Auto-convert functionality chkAutoConvert.addEventListener('change', function() { localStorage.setItem('autoConvert', this.checked); if (this.checked && inputText.value.trim()) { performEncoding(); } }); // Real-time input monitoring for auto-convert let inputTimeout; inputText.addEventListener('input', function() { updateCharCounts(); if (chkAutoConvert.checked) { clearTimeout(inputTimeout); inputTimeout = setTimeout(performEncoding, 500); } }); // Encoding type change selEncodingType.addEventListener('change', function() { if (chkAutoConvert.checked && inputText.value.trim()) { performEncoding(); } }); // Initialize with a sample conversion setTimeout(() => { if (inputText.value.trim() && !outputText.value.trim()) { performEncoding(); } }, 500);