Escape HTML Entities
Escape HTML Entities is a reusable JavaScript snippet. Escapes HTML special characters to prevent XSS attacks and safely display user-generated content. The full implementation: function escapeHtml(str) { const map = { '&': '&', ' ': '>', '"': '"', "'": ''', '/': '/', } return str.replace(/[&<>"'/]/g, c => map[c]) } // Unescape HTML function unescapeHtml(str) { const map = { '&': '&', '<': ' ', '"': '"', ''': "'", '/': '/', } return str.replace(/&(?:amp|lt|gt|quot|#x27|#x2F);/g, c => map[c]) } // Usage escapeHtml(' alert("xss") ') // "<script>alert("xss")</script>" This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.