Categories
JavaScript Answers

How to escape HTML tags as HTML entities with JavaScript?

Spread the love

To escape HTML tags as HTML entities with JavaScript, you can use a function to replace special characters like <, >, ", ', and & with their corresponding HTML entities.

To do this, we can write:

function escapeHtml(html) {
    return html.replace(/</g, "&lt;")
               .replace(/>/g, "&gt;")
               .replace(/"/g, "&quot;")
               .replace(/'/g, "&#39;")
               .replace(/&/g, "&amp;");
}

var unescapedHtml = "<div>Hello, world!</div>";
var escapedHtml = escapeHtml(unescapedHtml);
console.log(escapedHtml); // Output: "&lt;div&gt;Hello, world!&lt;/div&gt;"

In this example, the escapeHtml() function replaces occurrences of <, >, ", ', and & in the input string with their corresponding HTML entities using regular expressions and the replace() method.

We can then use this function to escape HTML tags in your JavaScript code.

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 *