/** * Escapes HTML special characters in a string to prevent Cross-Site Scripting (XSS) attacks. * This function should be used when displaying user-generated content in HTML. * It converts characters like <, >, &, ", ' to their HTML entity equivalents. * @param {string} str - The input string to escape. * @returns {string} The escaped string. */ function escapeHtml(str) { const div = document.createElement('div'); // Using textContent property is the safest way to escape HTML. // Assigning text to textContent automatically escapes HTML entities. div.appendChild(document.createTextNode(str)); return div.innerHTML; } /** * Alternative method using replace for specific known characters. * Less robust than DOM-based escaping for complex scenarios, but useful for quick sanitization * if DOM manipulation is not feasible or desired (e.g., in a Node.js context). * @param {string} str - The input string to escape. * @returns {string} The escaped string. */ function escapeHtmlManual(str) { return str .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } // --- Example Usage --- const userInput1 = ""; const userInput2 = "User's profile & settings."; const userInput3 = '

Hello World!

'; const safeOutput1 = escapeHtml(userInput1); const safeOutput2 = escapeHtml(userInput2); const safeOutput3 = escapeHtml(userInput3); console.log('Original 1:', userInput1); console.log('Escaped 1:', safeOutput1); // document.getElementById('output1').innerHTML = safeOutput1; console.log('Original 2:', userInput2); console.log('Escaped 2:', safeOutput2); // document.getElementById('output2').innerHTML = safeOutput2; console.log('Original 3:', userInput3); console.log('Escaped 3:', safeOutput3); // document.getElementById('output3').innerHTML = safeOutput3; const safeOutputManual1 = escapeHtmlManual(userInput1); console.log('Manual Escaped 1:', safeOutputManual1); /* // To see the effect in HTML, uncomment the following (requires an HTML file): //
//
//
*/