What is escape-html?
The escape-html package is designed to provide a simple and efficient way to escape HTML entities in strings. This is particularly useful to prevent XSS (Cross-Site Scripting) attacks by sanitizing user input or any data that might be dynamically inserted into HTML documents. The primary functionality of this package is to convert characters like '<', '>', '&', '"', and "'" into their corresponding HTML entities, making the output safe to include in HTML content.
What are escape-html's main functionalities?
Escaping HTML entities
This feature allows the conversion of potentially dangerous characters into their safe HTML entity equivalents. The provided code sample demonstrates how to use the escape-html package to escape a string that contains HTML and JavaScript, which could be harmful if rendered directly in a web page.
"const escapeHtml = require('escape-html');\nconst unsafeString = '<script>alert(\"XSS\")</script>';\nconst safeString = escapeHtml(unsafeString);\nconsole.log(safeString); // Output: <script>alert("XSS")</script>"
Other packages similar to escape-html
he
The 'he' package is a robust HTML entity encoder/decoder written in JavaScript. Unlike escape-html, which primarily focuses on escaping strings for safe HTML insertion, 'he' offers more comprehensive functionalities including the ability to decode HTML entities back to their original form. This makes 'he' more versatile for handling HTML entities in various contexts.
sanitize-html
While escape-html is focused on escaping strings to prevent XSS attacks, 'sanitize-html' goes a step further by allowing detailed configuration of what HTML tags and attributes are allowed. It can remove or sanitize HTML to a whitelist of allowed elements and attributes, making it a more comprehensive solution for sanitizing HTML content beyond just escaping entities.
escape-html
Escape string for use in HTML
Example
var escape = require('escape-html');
var html = escape('foo & bar');
Benchmark
$ npm run-script bench
> escape-html@1.0.3 bench nodejs-escape-html
> node benchmark/index.js
http_parser@1.0
node@0.10.33
v8@3.14.5.9
ares@1.9.0-DEV
uv@0.10.29
zlib@1.2.3
modules@11
openssl@1.0.1j
1 test completed.
2 tests completed.
3 tests completed.
no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled)
single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled)
many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled)
License
MIT