How to know if a URL is decoded/encoded?

后端 未结 5 797
后悔当初
后悔当初 2021-02-05 04:37

I am using Javascript method decodeURIComponent to decode an encoded URL. Now I am having an issue, that sometimes the URL is get encoded twice during redirection b

5条回答
  •  既然无缘
    2021-02-05 05:30

    There is a simple way to konw if a URL string is encoded.

    Take the initial string and compare it with the result of decoding it. If the result is the same, the string is not encoded; if the result is different then it is encoded.

    I had this issue with my urls and I used this functions:

    function isEncoded(uri) {
      uri = uri || '';
    
      return uri !== decodeURIComponent(uri);
    }
    

    So now I can use isEncoded as the discriminant in a while loop (or with recursion) to know if I need to keep calling decodeURIComponent on the string:

    function fullyDecodeURI(uri){
    
      while (isEncoded(uri)){
        uri = decodeURIComponent(uri);
      }
    
      return uri;
    }
    

    This solved the problem for me of decoding urls encoded multiple times. Hope this helps.

提交回复
热议问题