')); \n// Result: <script>alert("XSS")</script>\n\n\nThis approach achieves safe rendering while avoiding XSS vulnerabilities when updating DOM elements with dynamic text.","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Alex Kataev","url":"https://explain.codes//author/alex-kataev"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2024-12-29T19:15:01.579Z","dateModified":"2024-12-29T19:15:03.327Z"}
Explain Codes LogoExplain Codes Logo

Can I escape HTML special chars in JavaScript?

javascript
html-escaping
security-best-practices
javascript-libraries
Alex KataevbyAlex Kataev·Dec 29, 2024
TLDR

To safeguard against potential code injections, escape HTML special chars in JavaScript using a custom utility function. Primarily, we target these characters: &, <, >, ", ', and `. The below snippet exemplifies this:

function escapeHtml(str) { // Align the scape(y) sequences in an orderly fashion return str .replace(/&/g, '&amp;') // Finders keepers, ampersand weepers! .replace(/</g, '&lt;') // Less than perfect, more than adequate .replace(/>/g, '&gt;') // G(rea)Te job! .replace(/"/g, '&quot;') // Quote them right, keep them tight .replace(/'/g, '&#39;') // 'Single' issue party .replace(/`/g, '&#x60;'); // `Its party time, folks!` }

Example application for context:

console.log(escapeHtml('<script>alert("XSS")</script>')); // Result: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

This approach achieves safe rendering while avoiding XSS vulnerabilities when updating DOM elements with dynamic text.

Efficient escaping in multiple contexts

Different scenarios might require alternative methods or libraries to perform HTML escaping. This section details potential alternatives or enhancements to the initial custom solution.

When and where to escape

Knowing when to escape special HTML characters is as important as knowing how. The following scenarios often require special attention:

  1. User-generated content: User input may contain unpredictable or potentially harmful scripts.
  2. Template literals: Any variable values injected into templates should be escaped to prevent unwanted HTML interpretation.
  3. External API responses: Any data fetched from API endpoints displayed on your page should be safely escaped.

Consistently applying escape methods in these situations can significantly reduce security risks.

Libraries to the rescue

If your project already uses Lodash or jQuery, you can leverage their built-in functions to escape special HTML characters:

_.escape('<script>alert("XSS")</script>'); // Lodash $('#element').text('<script>alert("XSS")</script>'); // jQuery

Browser compatibility

Our escapeHtml function uses String.prototype.replace() with a global regex for full browser compatibility. Note that replaceAll, although tidier, may not work in some older browsers.

Live data handling

Escaping HTML characters on-the-fly is a common requirement for live chat or comment inputs. Simply attach an event listener to perform real-time escaping:

inputElement.addEventListener('input', function(e) { e.target.value = escapeHtml(e.target.value); // Live and let escape! });

Dom manipulation

Avoid using innerHTML because it might unintentionally execute HTML and JavaScript. Instead, create a dedicated DOM element and append it to the desired location:

const textNode = document.createTextNode('<script>alert("XSS")</script>'); // Creating a harmless text node paragraphElement.appendChild(textNode); // Safe passage into the DOM

The textContent property is another safe option to handle text which works uniformly across all modern web browsers.