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, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}How it works
- The input is converted to a string.
- Ampersands are converted to the
&HTML entity (must be done first) - 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.
| Name | Character | Entity | |
|---|---|---|---|
| Ampersand | & | & | Prevents starting HTML entities. The ampersand must be encoded first because subsequent replacements will add ampersands to the string. |
| Less Than | < | < | Prevents opening HTML tags. |
| Greater Than | > | > | Prevents closing HTML tags. |
| Double Quote | “ | " | Prevents breaking out of double-quoted HTML attributes. |
| Single Quote | ‘ | ' | Prevents breaking out of single-quoted HTML attributes. |
Contexts
Context refers to the type of surrounding content into which plain text is written:
| Context | Example | use escapeHtml? |
|---|---|---|
| HTML element | inner text of <TD> tag | Yes |
| HTML attribute | value of alt attribute | Yes – except attributes used for inline JavaScript such as onclick. |
| CSS | value of property | No |
| JavaScript | value of a variable | No |
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
- Cross Site Scripting Prevention – OWASP Cheat Sheet Series (owasp.org) – This cheatsheet contains techniques to prevent or limit the impact of XSS. Since no single technique will solve XSS, using the right combination of defensive techniques will be necessary to prevent XSS.

Leave a Reply