0

My string has & and I want to replace it with the percentage encoding (%26). This is just an example. There can be any escape character.
I tried this but it is not replacing & with %26 :

password.text?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
Nitish
  • 13,845
  • 28
  • 135
  • 263
  • Its an allowed character in the url, if you need to encode that then have to create your own character set or replace manually – Tj3n Mar 31 '17 at 07:14
  • May be this will helps you http://stackoverflow.com/a/43054388/6433023 – Nirav D Mar 31 '17 at 12:16

1 Answers1

0

How about this short string extension:

extension String
{
    func encode(_ chars: String) -> String
    {
        let forbidden = CharacterSet(charactersIn: chars)
        return self.addingPercentEncoding(withAllowedCharacters: forbidden.inverted) ?? self
    }
}

print("I can't read ENCODED text".encode("CDENO"))
// will print: I can't read %45%4E%43%4F%44%45%44 text

print("Command & Conquer".encode("&"))
// will print: Command %26 Conquer
LimeRed
  • 1,278
  • 13
  • 18