What characters need to be escaped in HTML?
Answer: It depends upon the context. Some possible contexts in HTML:
Inside of an element, this just includes the entity escape ampersand &
and the element delimiter less-than and greater-than signs <
>
:
These are three main characters which should be always escaped in your HTML and XML files,
& becomes &
< becomes <
> becomes >
Inside of attribute values you must also escape the quote character you’re using:
" becomes "
' becomes '
How to HTML escape characters example
HTML example code escape and unescape char using JavaScript.
<!DOCTYPE html>
<html>
<body>
<div class="half first"><textarea id="input" placeholder='Paste your HTML in here...' spellcheck="false" autofocus></textarea></div>
<div class="middle">
<select id="method">
<option value="escape">escape</option>
<option value="unescape">unescape</option>
</select>
</div>
<div class="half last"><textarea id="output" placeholder='Output...' spellcheck="false"></textarea></div>
<script>
// Escape & Unescape HTML:
(function() {
var escapeEl = document.createElement('textarea');
window.escapeHTML = function(html) {
escapeEl.textContent = html;
return escapeEl.innerHTML;
};
window.unescapeHTML = function(html) {
escapeEl.innerHTML = html;
return escapeEl.textContent;
};
})();
// getElementById shortcut:
var $ = function(id, scopeEl) {
return (scopeEl || document).getElementById(id);
};
// Grab the needed elements:
var inputEl = $('input');
var outputEl = $('output');
var methodToggleEl = $('method');
// Handle input:
function inputHandler() {
outputEl.value = window[methodToggleEl.value + 'HTML'](inputEl.value);
}
inputHandler();
methodToggleEl.onchange = inputEl.oninput = inputHandler;
</script>
</body>
</html>
Output:
Some Useful HTML Character Entities
Result | Description | Entity Name | Entity Number |
---|---|---|---|
non-breaking space | |   | |
< | less than | < | < |
> | greater than | > | > |
& | ampersand | & | & |
“ | double quotation mark | " | " |
‘ | single quotation mark (apostrophe) | ' | ' |
¢ | cent | ¢ | ¢ |
£ | pound | £ | £ |
¥ | yen | ¥ | ¥ |
€ | euro | € | € |
© | copyright | © | © |
® | registered trademark | ® | ® |
Do comment if you have any doubts and suggestions on this HMTL escape code.
Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version