neutralts::utils

Function escape_chars

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

Escapes special characters in a given input string.

This function replaces specific ASCII characters with their corresponding HTML entities. It is designed to handle both general HTML escaping and optional escaping of curly braces ({ and }).

§Arguments

  • input - The input string to escape.
  • escape_braces - A boolean flag indicating whether to escape curly braces ({ and }).
    • If true, curly braces are escaped as { and }.
    • If false, curly braces are left unchanged.

§Escaped Characters

The following characters are always escaped:

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

If escape_braces is true, the following characters are also escaped:

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

§Examples

Basic usage without escaping curly braces:

let input = r#"Hello, <world> & "friends"! {example}"#;
let escaped = escape_chars(input, false);
assert_eq!(escaped, r#"Hello, &lt;world&gt; &amp; &quot;friends&quot;! {example}"#);

Escaping curly braces:

let input = r#"Hello, <world> & "friends"! {example}"#;
let escaped = escape_chars(input, true);
assert_eq!(escaped, r#"Hello, &lt;world&gt; &amp; &quot;friends&quot;! &#123;example&#125;"#);