File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // Copyright 2018-2026 the Deno authors. MIT license.
2+ // This module is browser compatible.
3+
4+ const HTML_UNESCAPE_MAP : Record < string , string > = {
5+ "&" : "&" ,
6+ "<" : "<" ,
7+ ">" : ">" ,
8+ """ : '"' ,
9+ "'" : "'" ,
10+ "'" : "'" ,
11+ "/" : "/" ,
12+ } ;
13+
14+ const HTML_UNESCAPE_REGEXP = / & (?: a m p | l t | g t | q u o t | # (?: 3 9 | x 2 7 | x 2 F ) ) ; / g;
15+
16+ /**
17+ * Unescapes HTML special characters in a string.
18+ *
19+ * @param input The string to unescape
20+ * @returns The unescaped string
21+ *
22+ * @example Usage
23+ * ```ts
24+ * import { unescapeHtml } from "@std/text/unescape-html";
25+ * import { assertEquals } from "@std/assert";
26+ *
27+ * assertEquals(unescapeHtml("<script>alert('xss')</script>"), "<script>alert('xss')</script>");
28+ * ```
29+ */
30+ export function unescapeHtml ( input : string ) : string {
31+ return input . replace (
32+ HTML_UNESCAPE_REGEXP ,
33+ ( entity ) => HTML_UNESCAPE_MAP [ entity ] ! ,
34+ ) ;
35+ }
Original file line number Diff line number Diff line change 1+ // Copyright 2018-2026 the Deno authors. MIT license.
2+
3+ import { assertEquals } from "@std/assert" ;
4+ import { unescapeHtml } from "./unescape_html.ts" ;
5+
6+ Deno . test ( "unescapeHtml() unescapes HTML entities" , ( ) => {
7+ assertEquals (
8+ unescapeHtml ( "<script>alert('xss')</script>" ) ,
9+ "<script>alert('xss')</script>" ,
10+ ) ;
11+ } ) ;
12+
13+ Deno . test ( "unescapeHtml() unescapes ampersand" , ( ) => {
14+ assertEquals ( unescapeHtml ( "a & b" ) , "a & b" ) ;
15+ } ) ;
16+
17+ Deno . test ( "unescapeHtml() handles strings without entities" , ( ) => {
18+ assertEquals ( unescapeHtml ( "hello" ) , "hello" ) ;
19+ } ) ;
20+
21+ Deno . test ( "unescapeHtml() handles empty string" , ( ) => {
22+ assertEquals ( unescapeHtml ( "" ) , "" ) ;
23+ } ) ;
You can’t perform that action at this time.
0 commit comments