Function escape_chars

Source
pub fn escape_chars<'a>(input: &'a str, escape_braces: bool) -> Cow<'a, str>
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 &#123; and &#125;.
    • If false, curly braces are left unchanged.

§Escaped Characters

The following characters are always escaped:

  • &&amp;
  • <&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;"#);