/** * 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 = '