Skip to content

Instantly share code, notes, and snippets.

@YaronMiro
Created December 16, 2021 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YaronMiro/ecbed7a531326fa906b9d90e74913a93 to your computer and use it in GitHub Desktop.
Save YaronMiro/ecbed7a531326fa906b9d90e74913a93 to your computer and use it in GitHub Desktop.
Escape all quotes (single or double), text may include such characters. Good for dynamic text for HTML attributes.
// We have 2 capture groups of each quote type, and than replace each on with
"h\"ell'o there".replace(/(")|(')/g, '\\$1$2');
const escapeHtml = (unsafeText) => {
return unsafeText
.replaceAll('&', '&')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#039;');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment