1

I have the following string from a server:

I agree with the <a>((http://example.com)) Terms of Use</a> and I've read the <a>((http://example2.com)) Privacy</a>

now I want to show it like this in a label:

I agree with the <a href="http://google.com">Terms of Use</a> and I've read the <a href="http://google.com">Privacy</a>

I tried to cut of the ((http://example.com)) from the string and save it in another String. I need the link because the text should be clickable later.

I tried this to get the text that I want:

//the link:
let firstString = "(("
let secondString = "))"

let link = (text.range(of: firstString)?.upperBound).flatMap { substringFrom in
    (text.range(of: secondString, range: substringFrom..<text.endIndex)?.lowerBound).map { substringTo in
    String(text[substringFrom..<substringTo])
    }
}

//the new text
if let link = link {
    newString = text.replacingOccurrences(of: link, with: kEmptyString)
}

I got this from here: Swift Get string between 2 strings in a string

The problem with this is that it only removes the text inside the (( )) brackets. The brackets are still there. I tried to play with the offset of the indexes but this doesn't changed anything. Moreover this solution works if there's only one link in the text. If there are multiple links I think they should be stored and I have to loop through the text. But I don't know how to do this. I tried many things but I don't get this working. Is there maybe an easier way to get what I want to do?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Marcel
  • 472
  • 2
  • 6
  • 19

2 Answers2

2

You can use a regular expression to do a quick search replace.

let text = "I agree with the <a>((http://example.com)) Terms of Use</a> and I've read the <a>((http://example2.com)) Privacy</a>"
let resultStr = text.replacingOccurrences(of: "<a>\\(\\(([^)]*)\\)\\) ", with: "<a href=\"$1\">", options: .regularExpression, range: nil)
print(resultStr)

Output:

I agree with the <a href="http://example.com">Terms of Use</a> and I've read the <a href="http://example2.com">Privacy</a>

rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

You can use something like this to get the links:

let s = "I agree with the ((http://example.com)) Terms of Use and I've read the ((http://example2.com)) Privacy"

let firstDiv = s.split(separator: "(") // ["I agree with the ", "http://example.com)) Terms of Use and I\'ve read the ", "http://example2.com)) Privacy"]
let mid = firstDiv[1] // http://example.com)) Terms of Use and I've read the
let link1 = mid.split(separator: ")")[0] // http://example.com
let link2 = firstDiv[2].split(separator: ")")[0] // http://example2.com
Tob
  • 985
  • 1
  • 10
  • 26