Skip to content

Sanitize Class

The Sanitize class provides HTML and XSS sanitization.

s = new Sanitize

s.html(cInput)

Sanitize HTML by stripping dangerous tags, keeping safe ones.

safe = s.html('<script>alert("xss")</script><p>Safe</p>')
# Returns: "<p>Safe</p>"

s.strict(cInput)

Strictly sanitize HTML by stripping all tags.

text = s.strict('<b>Bold</b> <script>evil()</script>')
# Returns: "Bold evil()"

s.escapeHtml(cInput)

Escape HTML special characters to entities.

escaped = s.escapeHtml('<div class="test">Hello & goodbye</div>')
# Returns: "&lt;div class=&quot;test&quot;&gt;Hello &amp; goodbye&lt;/div&gt;"

s.escapeAttr(cInput)

Escape string for safe use in HTML attribute values (including unquoted).

escaped = s.escapeAttr('x onerror=alert(1)')
# Returns: "x onerror&#x3D;alert(1)"

s.escapeJs(cInput)

Escape string for safe use in JavaScript string literals.

escaped = s.escapeJs("hello 'world'" + nl + "newline")
# Returns: "hello \'world\' \n newline"

s.escapeUrl(cInput)

URL-encode string for safe embedding in URL query values.

encoded = s.escapeUrl("hello world&foo=bar")
# Returns: "hello%20world%26foo%3Dbar"