skip to Main Content

This is my simple extension:

extension String {
    var urlDecoded: String? {
        replacingOccurrences(of: "+", with: "%20").removingPercentEncoding
    }
}

And here is my string:

let string = "https%253A%252F%252Fplz.pl"

After I call

let firstDecoded = string.urlDecoded

// "https%3A%2F%2Fplz.pl"

let secondDecoded = string.urlDecoded?.urlDecoded

// "https://plz.pl"

Why do I have to call it twice? How can I do it correctly and quickly?

2

Answers


  1. Because the input is encoded twice.

    %253A: %25 is an encoded % meaning it results in %3A after the first decoding and : after the second decoding.

    Login or Signup to reply.
  2. Why do you have to decode it twice? Because it’s been encoded twice.

    The ASCII code point for the percent symbol is 0x25. So %25 in an encoded URL encodes a percent symbol. Thus:

    https%253A%252F%252Fplz.pl
         └┬┘  └┬┘  └┬┘
    https % 3A % 2F % 2Fplz.pl
          └┬─┘ └┬─┘ └┬─┘
    https  :    /    /  plz.pl
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search