Search code examples
javascripthtml

Can I escape HTML special chars in JavaScript?


I want to display text to HTML by a JavaScript function. How can I escape HTML special characters in JavaScript? Is there an API?


Solution

  • Here's a solution that will work in practically every web browser:

    function escapeHtml(unsafe)
    {
        return unsafe
             .replace(/&/g, "&")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;")
             .replace(/"/g, "&quot;")
             .replace(/'/g, "&#039;");
     }
    

    If you only support modern web browsers (2020+), then you can use the new replaceAll function:

    const escapeHtml = (unsafe) => {
        return unsafe.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#039;');
    }