How to escape HTML in a string
Short answer
Replace the five special characters with their HTML entities. The ampersand goes first, otherwise the other replacements would be broken:
const escapeHtml = (text) =>
text
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
console.log(escapeHtml('<b>Tom & Jerry</b>'));Output:
<b>Tom & Jerry</b>Easier on a page: textContent
When you insert text into an element, use textContent. The browser shows it as is and never turns it into tags:
<p id="comment"></p>
<script>
const userText = '<img src=x onerror=alert(1)>';
document.getElementById('comment').textContent = userText;
</script>Common mistake
Inserting user text through innerHTML without escaping lets anyone run their own code on your page:
// dangerous: the text becomes real HTML
element.innerHTML = userText;
// safe
element.textContent = userText;Functions used in this recipe
- String.prototype.replaceAll — Replaces all occurrences of a substring with another string.