Sanchit Paurush Sanchit Paurush - 1 month ago 10x
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.

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

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


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

var string = "Hello Google, hello 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
// Hello <href=""></a> Google, hello <href=""></a> Apple.