1

Some url strings in backend response is url encoded, while some are not. How to pick out those not encoded?


Updated:

Given that there are three kind of strings:

  • valid url string, url-encoded;

  • valid url string, original(not url-encoded);

  • invalid url string.

What I wanna do is creating URL from the first two kinds of strings.

With those in first kind, I'll just call init?(string:).

With those in second kind, I'll have to encode them before calling init?(string:)

So how to efficiently and elegantly create URL instances from those strings?

wzso
  • 3,482
  • 5
  • 27
  • 48
  • 6
    Why do you need to know? Just decode either way. If it's not encoded then decoding won't doing anything. – rmaddy Jul 08 '19 at 05:20

2 Answers2

1

Check the accepted answer from: How to find out if string has already been URL encoded?

It says: Decode, compare to original. If it does differ, original is encoded. If it doesn't differ, original isn't encoded. But still it says nothing about whether the newly decoded version isn't still encoded. A good task for recursion.

Since, you are working on your own API response and the url string will be either encoded or plain text; you can just decode once and compare with the original string.

Straight-forward: Decode and check if if it matches with original string.

  1. match - use the original string to check for valid url using regexp
  2. not a match - use the decoded string for valid url using regexp.
user_1989
  • 375
  • 4
  • 10
0

A simple hack is You can use regexp to check whether the string contains whitespace which you usually won't get in URL-encoded string. That may help you achieve your goal. Otherwise the comment of @rmaddy is also a fine choice.

Zabih Ullah
  • 575
  • 5
  • 14