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, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/&/g, "&");
}
var unescapedHtml = "<div>Hello, world!</div>";
var escapedHtml = escapeHtml(unescapedHtml);
console.log(escapedHtml); // Output: "<div>Hello, world!</div>"
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.