@satyajit_me/xss-sanitizer
v1.0.1
Published
Clean and sanitize HTML to prevent XSS attacks
Maintainers
Readme
XSS Sanitizer
Clean and sanitize HTML to prevent XSS attacks.
Installation
npm install xss-sanitizerQuick Start
import { sanitize, escapeHtml, stripTags } from 'xss-sanitizer';
// Sanitize HTML (keep safe tags, remove dangerous ones)
sanitize('<p onclick="alert(1)">Hello <script>evil</script></p>')
// '<p>Hello </p>'
// Escape all HTML
escapeHtml('<script>alert("xss")</script>')
// '<script>alert("xss")</script>'
// Remove all tags
stripTags('<p>Hello <b>World</b></p>')
// 'Hello World'API
escapeHtml(str)
Escapes HTML entities (<, >, &, ", ', etc.)
escapeHtml('<script>') // '<script>'unescapeHtml(str)
Reverses HTML entity escaping.
stripTags(html)
Removes all HTML tags, keeping only text.
stripTags('<p>Hello <b>World</b></p>') // 'Hello World'sanitize(html, options)
Smart sanitization - keeps safe tags, removes dangerous ones.
// Basic usage
sanitize('<p onclick="evil()">Hello</p>')
// '<p>Hello</p>'
// Options
sanitize(html, {
allowedTags: ['p', 'b', 'i', 'a'], // Override allowed tags
allowedAttributes: { // Override allowed attrs
'*': ['class'],
'a': ['href']
},
stripAll: true, // Remove ALL tags
escapeAll: true // Escape ALL HTML
})isSafeUrl(url)
Check if URL is safe (no javascript:, data:, etc.)
isSafeUrl('https://example.com') // true
isSafeUrl('javascript:alert(1)') // falsesanitizeUrl(url)
Returns safe URL or empty string.
sanitizeText(text)
Full HTML escaping for user text display.
Default Allowed Tags
a, b, blockquote, br, code, div, em, h1-h6, hr, i, img, li, ol, p, pre, span, strong, table, td, th, tr, ul, and more.
License
MIT
