1
- # Handles encoding and decoding of HTML entities .
1
+ # Provides HTML escaping and unescaping methods .
2
2
module HTML
3
- SUBSTITUTIONS = {
4
- '!' => " !" ,
5
- '"' => " "" ,
6
- '$' => " $" ,
7
- '%' => " %" ,
8
- '&' => " &" ,
9
- '\' ' => " '" ,
10
- '(' => " (" ,
11
- ')' => " )" ,
12
- '=' => " =" ,
13
- '>' => " >" ,
14
- '<' => " <" ,
15
- '+' => " +" ,
16
- '@' => " @" ,
17
- '[' => " [" ,
18
- ']' => " ]" ,
19
- '`' => " `" ,
20
- '{' => " {" ,
21
- '}' => " }" ,
22
- '\u{a0}' => " " ,
3
+ private SUBSTITUTIONS = {
4
+ '&' => " &" ,
5
+ '<' => " <" ,
6
+ '>' => " >" ,
7
+ '"' => " "" ,
8
+ '\' ' => " '" ,
23
9
}
24
10
25
- # Encodes a string with HTML entity substitutions.
11
+ # Escapes special characters in HTML, namely
12
+ # `&`, `<`, `>`, `"` and `'`.
26
13
#
27
14
# ```
28
15
# require "html"
@@ -33,25 +20,29 @@ module HTML
33
20
string.gsub(SUBSTITUTIONS )
34
21
end
35
22
36
- # Encodes a string to HTML, but writes to the `IO` instance provided.
23
+ # Same as `escape(string)` but ouputs the result to
24
+ # the given *io*.
37
25
#
38
26
# ```
39
27
# io = IO::Memory.new
40
28
# HTML.escape("Crystal & You", io) # => nil
41
29
# io.to_s # => "Crystal & You"
42
30
# ```
43
- def self.escape (string : String , io : IO )
31
+ def self.escape (string : String , io : IO ) : Nil
44
32
string.each_char do |char |
45
33
io << SUBSTITUTIONS .fetch(char, char)
46
34
end
47
35
end
48
36
49
- # Decodes a string that contains HTML entities.
37
+ # Returns a string where some named and all numeric character references
38
+ # (e.g. >, >, &x3e;) in *string* are replaced with the corresponding
39
+ # unicode characters. Only these named entities are replaced:
40
+ # apos, amp, quot, gt, lt and nbsp.
50
41
#
51
42
# ```
52
43
# HTML.unescape("Crystal & You") # => "Crystal & You"
53
44
# ```
54
- def self.unescape (string : String )
45
+ def self.unescape (string : String ) : String
55
46
return string unless string.includes? '&'
56
47
57
48
string.gsub(/&(apos|amp|quot|gt|lt|nbsp|\# [0-9] +|\# [xX][0-9A-Fa-f] +) ;/ ) do |string , _match |
0 commit comments