Sanchit Paurush Sanchit Paurush - 2 months ago 26
iOS Question

Add character at start and end of SubString from String in iOS Swift

I am working on a project where I need to add character at start and end of substring from String.
Example

Given String
"Hello http://google.com Google."
Result should be
"Hello <a href="">http://www.google.com</a> The site for google."


Please note I am not sure about the location of substring as it is dynamic.
Please advice.

Answer

You can use NSDataDetector to find links embedded in the string, and then replace these. Example (explanations inline):

var string = "Hello http://google.com Google, hello http://www.apple.com Apple."
var nsString = string as NSString // NSString needed in order to work with NSRange

// Data detector for embedded links:
let detector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue)
let matches = detector.matchesInString(string, options: [],
                                       range: NSRange(location: 0, length: nsString.length))

// Replace links, starting with the last one, otherwise ranges would change:
for match in matches.reverse() {
    if let url = match.URL {
        let replacement = "<href=\"\(url.absoluteString)\"></a>"
        nsString = nsString.stringByReplacingCharactersInRange(match.range, withString: replacement)
    }
}
string = nsString as String
print(string)
// Hello <href="http://google.com"></a> Google, hello <href="http://www.apple.com"></a> Apple.