What is escape-goat?
The escape-goat package is a utility for escaping and unescaping HTML entities in strings. It is useful for preventing XSS attacks by sanitizing user input or rendering text in a web application.
What are escape-goat's main functionalities?
Escape HTML
Escapes HTML entities in a string to prevent XSS attacks or render text safely in HTML documents. The code sample demonstrates how to escape a string containing HTML tags and entities.
"<div>Hello & 'world'</div>".escape()
Unescape HTML
Unescapes HTML entities in a string. This is useful when you need to convert sanitized text back to its original form for editing or processing. The code sample shows how to unescape a string that contains escaped HTML entities.
"<div>Hello & 'world'</div>".unescape()
Other packages similar to escape-goat
he
The 'he' package is a robust HTML entity encoder/decoder written in JavaScript. It supports all named character references defined in HTML, handling even obscure and rare entities. Compared to escape-goat, 'he' offers a more comprehensive set of features for encoding and decoding HTML entities.
escape-html
The 'escape-html' package is a simple and fast utility for escaping HTML entities in strings. It is focused solely on escaping strings to prevent XSS attacks, similar to escape-goat's escaping functionality, but does not provide unescaping capabilities.
entities
The 'entities' package is a comprehensive library for encoding and decoding HTML/XML entities. It offers a wide range of functionalities, including support for numerous character encodings. It is more feature-rich compared to escape-goat, which has a more minimalistic approach.
Escape a string for use in HTML or the inverse
Install
$ npm install escape-goat
Usage
import {htmlEscape, htmlUnescape} from 'escape-goat';
htmlEscape('🦄 & 🐐');
htmlUnescape('🦄 & 🐐');
htmlEscape('Hello <em>World</em>');
const url = 'https://sindresorhus.com?x="🦄"';
htmlEscape`<a href="${url}">Unicorn</a>`;
const escapedUrl = 'https://sindresorhus.com?x="🦄"';
htmlUnescape`URL from HTML: ${escapedUrl}`;
API
htmlEscape(string)
Escapes the following characters in the given string
argument: &
<
>
"
'
The function also works as a tagged template literal that escapes interpolated values.
htmlUnescape(htmlString)
Unescapes the following HTML entities in the given htmlString
argument: &
<
>
"
'
The function also works as a tagged template literal that unescapes interpolated values.
Tip
Ensure you always quote your HTML attributes to prevent possible XSS.
FAQ
Why yet another HTML escaping package?
I couldn't find one I liked that was tiny, well-tested, and had both escape and unescape methods.