Categories
Tutorials

Escaping HTML in JS shouldn’t be painful… but it is.

JavaScript doesn’t have a direct equivalent to PHP’s htmlentities function, which converts characters to their HTML entities to prevent issues like XSS (Cross-Site Scripting). However, JavaScript does have ways to safely handle strings for insertion into the DOM.

1. Using textContent or innerText

When you use innerText or textContent to insert a string into the DOM, the browser automatically escapes any HTML-like characters, making it safe. For example:

const element = document.getElementById('example');
element.textContent = '<script>alert("XSS")</script>';

This will display the string as-is (<script>alert("XSS")</script>) in the browser, without executing the script.

2. Manually Escaping HTML

If you need to escape a string manually (e.g., for use in attributes or other contexts), you can create a utility function:

function escapeHTML(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}

// Example usage:
const safeString = escapeHTML('<script>alert("XSS")</script>');
console.log(safeString);
// Outputs: <script>alert("XSS")</script>

This approach uses the browser’s built-in escaping mechanism by leveraging a temporary DOM element.

3. Avoid encodeURIComponent or encodeURI

As you mentioned, encodeURIComponent and encodeURI are not suitable replacements for htmlentities. These functions are designed for encoding strings for use in URLs, not for escaping HTML. For example:

const urlSafe = encodeURIComponent('<script>alert("XSS")</script>');
console.log(urlSafe);
// Outputs: %3Cscript%3Ealert(%22XSS%22)%3C%2Fscript%3E

This is useful for URLs but won’t help with safely displaying content in the DOM.

Summary

  • Use textContent or innerText for safe DOM insertion.
  • Use a custom escapeHTML function for manual escaping.
  • Avoid using encodeURIComponent for HTML escaping—it serves a different purpose.

Hope this is a great help to you guys. If you know of a simpler way to do this, leave your comment below, I see you in the next project.

Remember to follow us in Facebook, YouTube, X, Truth Social and Gtter. Stop by and say “Hi”.

Happy Coding and Happy Designing… Designer’s Gate out.