DevToolsForYou

HTML Escape Tool in Rust — Code Examples

HTML Escape Tool in RustUse the online tool →

HTML escaping converts special characters like <, >, &, and " into their HTML entity equivalents (&lt;, &gt;, &amp;, &quot;) to prevent XSS attacks and ensure correct rendering. Here is how to escape and unescape HTML in each language.

The html-escape crate provides encode_text and decode_html_entities. For template rendering, askama and minijinja auto-escape by default.

Rust
// Cargo.toml: html-escape = "0.2"
use html_escape::{encode_text, decode_html_entities};

fn main() {
    let raw = r#"<script>alert("xss")</script> & "quotes""#;

    // Escape
    let escaped = encode_text(raw);
    println!("{}", escaped);
    // &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; &amp; &quot;quotes&quot;

    // Unescape
    let unescaped = decode_html_entities(&escaped);
    println!("{}", unescaped);
    // <script>alert("xss")</script> & "quotes"
}

// Without a crate — manually escape the 5 critical characters:
fn escape_html(s: &str) -> String {
    s.chars().map(|c| match c {
        '&'  => "&amp;".to_string(),
        '<'  => "&lt;".to_string(),
        '>'  => "&gt;".to_string(),
        '"'  => "&quot;".to_string(),
        ''' => "&#x27;".to_string(),
        c    => c.to_string(),
    }).collect()
}
Notes & gotchas
  • encode_text is for escaping text content; use encode_double_quoted_attribute for HTML attribute values.
  • The askama and minijinja template engines auto-escape output by default — no manual escaping needed.
  • The manual implementation is fine for simple cases but misses some edge cases that html-escape handles correctly.
Try it in your browser

Need to html escape/unescape without writing code? The HTML Escape Tool runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open HTML Escape/Unescape
HTML Escape Tool in other languages