-
Notifications
You must be signed in to change notification settings - Fork 0
/
String_Extension_HTML.swift
44 lines (43 loc) · 1.2 KB
/
String_Extension_HTML.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
extension String {
/// Returns the String with all special HTML characters encoded.
public var stringByEncodingHTML: String {
var ret = ""
var g = self.unicodeScalars.generate()
while let c = g.next() {
if c < UnicodeScalar(0x0009) {
ret.appendContentsOf("&#x");
ret.append(UnicodeScalar(0x0030 + UInt32(c)));
ret.appendContentsOf(";");
} else if c == UnicodeScalar(0x0022) {
ret.appendContentsOf(""")
} else if c == UnicodeScalar(0x0026) {
ret.appendContentsOf("&")
} else if c == UnicodeScalar(0x0027) {
ret.appendContentsOf("'")
} else if c == UnicodeScalar(0x003C) {
ret.appendContentsOf("<")
} else if c == UnicodeScalar(0x003E) {
ret.appendContentsOf(">")
} else if c > UnicodeScalar(126) {
ret.appendContentsOf("&#\(UInt32(c));")
} else {
ret.append(c)
}
}
return ret
}
/// Returns the String with all special URL characters encoded.
public var stringByEncodingURL: String {
var ret = ""
var g = self.utf8.generate()
while let c = g.next() {
if c.shouldURLEncode {
ret.append(UnicodeScalar(37))
ret.appendContentsOf(c.hexString)
} else {
ret.append(UnicodeScalar(c))
}
}
return ret
}
}