Skip to main content

max / makenotwork

793 B · 34 lines History Blame Raw
1 /// HTML-escape a string for safe interpolation into element content or attributes.
2 ///
3 /// Escapes all five HTML-significant characters: `& < > " '`.
4 pub(crate) fn html_escape(s: &str) -> String {
5 s.replace('&', "&amp;")
6 .replace('<', "&lt;")
7 .replace('>', "&gt;")
8 .replace('"', "&quot;")
9 .replace('\'', "&#x27;")
10 }
11
12 #[cfg(test)]
13 mod tests {
14 use super::*;
15
16 #[test]
17 fn escapes_all_five_chars() {
18 assert_eq!(
19 html_escape("A & B < C > D \" E ' F"),
20 "A &amp; B &lt; C &gt; D &quot; E &#x27; F"
21 );
22 }
23
24 #[test]
25 fn no_change_for_safe_string() {
26 assert_eq!(html_escape("hello world"), "hello world");
27 }
28
29 #[test]
30 fn empty_string() {
31 assert_eq!(html_escape(""), "");
32 }
33 }
34