Skip to main content

escape_text

Function escape_text 

Source
pub fn escape_text(s: &str) -> Cow<'_, str>
Expand description

Escapes special characters for HTML text content.

Returns borrowed input when no escaping is needed (common case), avoiding allocation overhead. Only &, <, and > are escaped.

§Performance

This function uses a fast-path check to avoid allocation when the input contains no special characters. In typical HTML content, 80-90% of text nodes require no escaping.

§Examples

use std::borrow::Cow;

use scrape_core::utils::escape_text;

// No escaping needed - returns borrowed reference
let result = escape_text("Hello World");
assert!(matches!(result, Cow::Borrowed(_)));
assert_eq!(result, "Hello World");

// Escaping needed - returns owned string
let result = escape_text("<script>alert('xss')</script>");
assert!(matches!(result, Cow::Owned(_)));
assert_eq!(result, "&lt;script&gt;alert('xss')&lt;/script&gt;");