Skip to content

Instantly share code, notes, and snippets.

@bobdobbalina
Created January 20, 2021 19:23
Show Gist options
  • Save bobdobbalina/769208a73dedb0fddcf40cc4378ee1ee to your computer and use it in GitHub Desktop.
Save bobdobbalina/769208a73dedb0fddcf40cc4378ee1ee to your computer and use it in GitHub Desktop.
Javascript: Escape the HTML tags
const escapeHTML = str =>
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;'
}[tag] || tag)
);
escapeHTML('<a href="#">Me & you</a>'); // &lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment