File tree 1 file changed +24
-0
lines changed
1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Handles encoding and decoding of HTML entities.
1
2
module HTML
2
3
SUBSTITUTIONS = {
3
4
'!' => " !" ,
@@ -21,16 +22,39 @@ module HTML
21
22
'\u{a0}' => " " ,
22
23
}
23
24
25
+ # Encodes a string with HTML entity substitutions.
26
+ #
27
+ # ```
28
+ # require "html"
29
+ #
30
+ # HTML.escape("Crystal & You") # => "Crystal & You"
31
+ # ```
24
32
def self.escape (string : String ) : String
25
33
string.gsub(SUBSTITUTIONS )
26
34
end
27
35
36
+ # Encodes a string to HTML, but writes to the IO instance provided.
37
+ #
38
+ # ```
39
+ # require "html"
40
+ #
41
+ # io = IO::Memory.new
42
+ # HTML.escape("Crystal & You", io) # => "Crystal & You"
43
+ # io.to_s # => "Crystal & You"
44
+ # ```
28
45
def self.escape (string : String , io : IO )
29
46
string.each_char do |char |
30
47
io << SUBSTITUTIONS .fetch(char, char)
31
48
end
32
49
end
33
50
51
+ # Decodes a string that contains HTML entities.
52
+ #
53
+ # ```
54
+ # require "html"
55
+ #
56
+ # HTML.unescape("Crystal & You") # => "Crystal & You"
57
+ # ```
34
58
def self.unescape (string : String )
35
59
return string unless string.includes? '&'
36
60
You can’t perform that action at this time.
0 commit comments