// // AttributedString+Trim.swift // Tusker // // Created by Shadowfacts on 8/29/18. // Copyright © 2018 Shadowfacts. All rights reserved. // import Foundation extension NSAttributedString { var fullRange: NSRange { return NSRange(location: 0, length: self.length) } } extension NSMutableAttributedString { func trimLeadingCharactersInSet(_ charSet: CharacterSet) { var end = string.startIndex while end < string.endIndex && charSet.contains(string.unicodeScalars[end]) { end = string.unicodeScalars.index(after: end) } if end > string.startIndex { let length = string.utf16.distance(from: string.startIndex, to: end) replaceCharacters(in: NSRange(location: 0, length: length), with: "") } } func trimTrailingCharactersInSet(_ charSet: CharacterSet) { if string.isEmpty { return } var start = string.index(before: string.endIndex) while start > string.startIndex && charSet.contains(string.unicodeScalars[start]) { start = string.unicodeScalars.index(before: start) } if start < string.endIndex { if start != string.startIndex || !charSet.contains(string.unicodeScalars[start]) { start = string.unicodeScalars.index(after: start) } let location = string.utf16.distance(from: string.startIndex, to: start) let length = string.utf16.distance(from: start, to: string.endIndex) replaceCharacters(in: NSRange(location: location, length: length), with: "") } } }