3

I have a string and I need to encode it in html. For example ">" becomes "& gt;" In C# I do

string stringEncoded = System.Net.HttpUtility.HtmlEncode(myString);

How can I do the same thing in Swift?

jjx
  • 257
  • 2
  • 9
  • I had already seen that page. I do not need to encode the text for a url. The code you linked transforms to %3C%3F aaa %3F%3E. instead the symbol "<" will become "&gt ;" – jjx Nov 26 '14 at 21:29

1 Answers1

3

Might be extremely late by now... At the moment I am doing it like this

    let html = "<pre>something</pre>"
    var result = html.stringByReplacingOccurrencesOfString("&", withString: "&amp;", options: nil, range: nil)
    result = result.stringByReplacingOccurrencesOfString("\"", withString: "&quot;", options: nil, range: nil)
    result = result.stringByReplacingOccurrencesOfString("'", withString: "&#39;", options: nil, range: nil)
    result = result.stringByReplacingOccurrencesOfString("<", withString: "&lt;", options: nil, range: nil)
    result = result.stringByReplacingOccurrencesOfString(">", withString: "&gt;", options: nil, range: nil)
    print(result)
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
rodrigoelp
  • 2,550
  • 1
  • 19
  • 29