Categories
JavaScript Answers

How to escape HTML special chars in JavaScript?

Spread the love

To escape HTML special chars in JavaScript, we call the replaceAll method.

For instance, we write

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

to define the escapeHtml function.

In it, we call replaceAll to replace all the strings in the first argument with the ones in the 2nd argument.

Therefore, all the HTML characters are replaced with their corresponding HTML entities.

The string with the replacements done is returned.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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