How to escape HTML special characters in JavaScript?

Spread the love

Sometimes, we want to escape HTML special characters in JavaScript.

In this article, we’ll look at how to escape HTML special characters in JavaScript.

How to escape HTML special characters in JavaScript?

To escape HTML special characters in JavaScript, we replace all the special HTML characters with HTML entities.

For instance, we write

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

to call replaceAll with the characters to replace and the HTML entities to replace them with respectively.

Conclusion

To escape HTML special characters in JavaScript, we replace all the special HTML characters with HTML entities.

Leave a Reply

Your email address will not be published.