@@ -37,50 +37,16 @@ import UIKit
3737
3838extension String {
3939
40- // Current implementation by @alexaubry in
41- // https://github.com/alexaubry/HTMLString
40+ private static let escapeAmpRegExp = try ! NSRegularExpression ( pattern : " &(?!(#[0-9]{2,4}|[A-z]{2,6});) " , options : NSRegularExpression . Options ( rawValue : 0 ) )
41+
4242 public func escapeWithUnicodeEntities( ) -> String {
43- var copy = self
44- copy. addUnicodeEntities ( )
45- return copy
46- }
47-
48- internal mutating func addUnicodeEntities( ) {
49- var position : String . Index ? = startIndex
50- let requiredEscapes : Set < Character > = [ " ! " , " \" " , " $ " , " % " , " & " , " ' " , " + " , " , " , " < " , " = " , " > " , " @ " , " [ " , " ] " , " ` " , " { " , " } " ]
51-
52- while let cursorPosition = position {
53- guard cursorPosition != endIndex else { break }
54- let character = self [ cursorPosition]
55-
56- if requiredEscapes. contains ( character) {
57- // One of the required escapes for security reasons
58- let escape = " &# \( character. asciiValue!) ; " // required escapes can can only be ASCII
59- position = positionAfterReplacingCharacter ( at: cursorPosition, with: escape)
60- } else {
61- // Not a required escape, no need to replace the character
62- position = index ( cursorPosition, offsetBy: 1 , limitedBy: endIndex)
63- }
64- }
43+ let range = NSRange ( location: 0 , length: self . count)
44+ return String . escapeAmpRegExp. stringByReplacingMatches ( in: self ,
45+ options: NSRegularExpression . MatchingOptions ( rawValue: 0 ) ,
46+ range: range,
47+ withTemplate: " & " )
6548 }
6649
67- /// Replaces the character at the given position with the escape and returns the new position.
68- fileprivate mutating func positionAfterReplacingCharacter( at position: String . Index , with escape: String ) -> String . Index ? {
69- let nextIndex = index ( position, offsetBy: 1 )
70-
71- if let fittingPosition = index ( position, offsetBy: escape. count, limitedBy: endIndex) {
72- // Check if we can fit the whole escape in the receiver
73- replaceSubrange ( position ..< nextIndex, with: escape)
74- return fittingPosition
75- } else {
76- // If we can't, remove the character and insert the escape to make it fit.
77- remove ( at: position)
78- insert ( contentsOf: escape, at: position)
79- return index ( position, offsetBy: escape. count, limitedBy: endIndex)
80- }
81- }
82-
83-
8450}
8551
8652extension NSNumber {
0 commit comments