JavaScript escapeHtml() function for safe HTML output

Updated on October 18, 2026

This reusable escapeHtml() function converts HTML-sensitive characters into their corresponding HTML entities, ensuring they are interpreted as text. It can be used when writing text inside an HTML element or attribute. The function helps prevent rendering issues and reduces the risk of cross-scripting attacks using HTML injection.

/**
 * Escapes text for insertion into HTML.
 *
 * Intended for:
 *   <div>${escapeHtml(value)}</div>
 *   <td>${escapeHtml(value)}</td>
 *
 * Not safe for:
 *   - CSS values
 *   - JavaScript strings
 *   - URLs
 */
function escapeHtml(value) {
  return String(value ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

How it works

  1. The input is converted to a string.
  2. Ampersands are converted to the &amp; HTML entity (must be done first)
  3. Other special characters are converted to their HTML entities.

The result is a string that can be safely inserted as text into an HTML element or attribute. The string is not safe to insert as text into CSS or JavaScript.

NameCharacterEntity
Ampersand&&amp;Prevents starting HTML entities. The ampersand must be encoded first because subsequent replacements will add ampersands to the string.
Less Than<&lt;Prevents opening HTML tags.
Greater Than>&gt;Prevents closing HTML tags.
Double Quote“&quot;Prevents breaking out of double-quoted HTML attributes.
Single Quote‘&#39;Prevents breaking out of single-quoted HTML attributes.

Contexts

Context refers to the type of surrounding content into which plain text is written:

ContextExampleuse escapeHtml?
HTML elementinner text of <TD> tagYes
HTML attributevalue of alt attributeYes – except attributes used for inline JavaScript such as onclick.
CSSvalue of propertyNo
JavaScriptvalue of a variableNo

The escapeHtml() function is intended to be used only when writing plain text into an HTML element or HTML attribute context. The escapeHtml() function is not safe in a CSS or JavaScript context.

Why do this?

A cross-scripting attack (XSS) occurs when an attacker is able to insert and execute malicious content on a website. Often the attacker is trying to get a <script> tag injected into a page that will be viewed by other visitors. That script can show a fake password prompt, or send data to an outside web service, etc. To accomplish this, the attacker looks for any way to get their <script> tag onto a page.

One common approach is to insert the <script> tag into user-supplied data, such as a profile name or location. If the website blindly accepts and writes back that data when constructing the page, the data will be interpreted as HTML. To illustrate, suppose a website dynamically constructs HTML as follows:

htmlToWrite = "<div>" + userProfile.firstName + "</div>"

If userProfile.firstName contains a <script> tag, then the script will get executed. The correct approach is to encode the potentially unsafe data:

htmlToWrite = "<p>" + escapeHtml(userprofile.firstName) + "</p>"

A similar approach occurs with HTML attributes. Consider the following unsafe code, which constructs an anchor tag with a user-supplied website address:

htmltoWrite = "<a href='" + userProfile.website + "'>my website</a>"

To exploit this unsafe code, the attacker uses a “website” value that closes the preceding anchor tag and then writes a script tag. For example:

'></a><script>maliciousScript()</script><a href='

To prevent this exploit:

htmltoWrite = "<a href='" + escapeHtml(userProfile.website) + "'>my website</a>"

Never trust input

Never assume a string is safe to insert as text. Even if you think a string came from a trusted source like your database or another script, those sources can be compromised. If you make a point to always escape strings intended as plain text, you keep a layer of protection against future bugs or attacks.

References

License

Licensed under CC BY 4.0 You are free to share and adapt this content for any purpose as long as you give appropriate credit in a reasonable manner.

No affiliate links

We do not participate in affiliate marketing, and we are not paid to mention products.

Leave a Reply

Your email address will not be published. Required fields are marked *