Search code examples
iosswiftxmldouble-quotessingle-quotes

Unable to replace string in Swift


Trying to escape few special characters of string for sending it via xml api.

Tried below code but not working for all the occurrences of Single Quote (') and Double Quote (")

var strToReturn = "“Hello” ‘world’"
strToReturn = strToReturn.replacingOccurrences(of: "&", with: "&")
strToReturn = strToReturn.replacingOccurrences(of: "<", with: "&lt;")
strToReturn = strToReturn.replacingOccurrences(of: ">", with: "&gt;")
strToReturn = strToReturn.replacingOccurrences(of: "‘", with: "&apos;")
strToReturn = strToReturn.replacingOccurrences(of: "“", with: "&quot;") 

print("Replaced string : \(strToReturn)") 

Result is &quot;Hello” &apos;world’

If anyone can help, thanks!


Solution

  • You need to specify replacement strings for and because ’ != ‘ and ” != “

    var strToReturn = "“Hello” ‘world’"
    strToReturn = strToReturn.replacingOccurrences(of: "&", with: "&amp;")
    strToReturn = strToReturn.replacingOccurrences(of: "<", with: "&lt;")
    strToReturn = strToReturn.replacingOccurrences(of: ">", with: "&gt;")
    strToReturn = strToReturn.replacingOccurrences(of: "‘", with: "&apos;")
    strToReturn = strToReturn.replacingOccurrences(of: "“", with: "&quot;")
    strToReturn = strToReturn.replacingOccurrences(of: "’", with: "&apos;")
    strToReturn = strToReturn.replacingOccurrences(of: "”", with: "&quot;")