How to remove single quotes from string in Swift?

Viewed 903

I receive value from API response like below

{
    "first_name" = "active EQ 'true'";
}

I need to send that value as a query parameter in another API. But when sending the request I see that URL is not being encoded. I am expecting that active EQ 'true' should be URL encoded as active%20EQ%20%27true%27.

I tried addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) and it resulted in "active%20EQ%20\'true\'. I see backslash is being added as escape character but not encoding as expected.

let k = "active EQ 'true'"
let j = k.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print("j is \(j)")

I expected the output as active%20EQ%20%27true%27, but the actual output is active%20EQ%20\'true\'

3 Answers

Omit " ' " from your string first. Check following code :

let k = "active EQ 'true' "
let i = k.replacingOccurrences(of: "'", with: "")
let j = i.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print("j is \(j!)")

Try this, I checked it and its working fine.

let k = "active EQ 'true'"
let j = escape(k)
print("j is \(j)")

func escape(_ string: String) -> String {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowedCharacterSet = CharacterSet.urlQueryAllowed
        allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")

        return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
    }

Result: j is active%20EQ%20%27true%27

Thanks for all suggestions and by EOD I don't want to encode single quotes as the API is working fine with that and value to API should be sent with single quotes only. I was just trying to know the possibilities of encoding this type of strings.

Related