neutralts::utils

Function unescape_chars

Source
pub fn unescape_chars(input: &str, escape_braces: bool) -> String
Expand description

Unescapes HTML entities in a given input string.

This function is designed specifically to reverse the escaping performed by escape_chars. It is not intended to be a general-purpose HTML decoder. It replaces the following HTML entities with their corresponding characters:

  • &&
  • &lt;<
  • &gt;>
  • &quot;"
  • &#x27;'
  • &#x2F;/

If escape_braces is true, it also replaces:

  • &#123;{
  • &#125;}

If an unrecognized entity is encountered, it is left unchanged in the output.

§Arguments

  • input - The input string containing HTML entities to unescape.
  • escape_braces - A boolean flag indicating whether to unescape curly braces ({ and }).
    • If true, &#123; and &#125; are unescaped to { and }.
    • If false, &#123; and &#125; are left unchanged.

§Examples

Basic usage:

let input = "&lt;script&gt;alert(&quot;Hello &amp; &#x27;World&#x27;&quot;);&lt;/script&gt;";
let unescaped = unescape_chars(input, false);
assert_eq!(unescaped, r#"<script>alert("Hello & 'World'");</script>"#);

Unescaping curly braces:

let input = "&#123;example&#125;";
let unescaped = unescape_chars(input, true);
assert_eq!(unescaped, "{example}");

Unrecognized entities are preserved:

let input = "This is an &unknown; entity.";
let unescaped = unescape_chars(input, false);
assert_eq!(unescaped, "This is an &unknown; entity.");