How to find out if string has already been URL encoded?

后端 未结 11 1045
死守一世寂寞
死守一世寂寞 2020-11-30 03:46

How could I check if string has already been encoded?

For example, if I encode TEST==, I get TEST%3D%3D. If I again encode last string, I

11条回答
  •  感情败类
    2020-11-30 04:22

    Thanks to this answer I coded a function (JS Language) that encodes the URL just once with encodeURI so you can call it to make sure is encoded just once and you don't need to know if the URL is already encoded.

    ES6:

    var getUrlEncoded = sURL => {
        if (decodeURI(sURL) === sURL) return encodeURI(sURL)
        return getUrlEncoded(decodeURI(sURL))
    }
    

    Pre ES6:

    var getUrlEncoded = function(sURL) {
        if (decodeURI(sURL) === sURL) return encodeURI(sURL)
        return getUrlEncoded(decodeURI(sURL))
    }
    

    Here are some tests so you can see the URL is only encoded once:

    getUrlEncoded("https://example.com/media/Screenshot27 UI Home.jpg")
    //"https://example.com/media/Screenshot27%20UI%20Home.jpg"
    getUrlEncoded(encodeURI("https://example.com/media/Screenshot27 UI Home.jpg"))
    //"https://example.com/media/Screenshot27%20UI%20Home.jpg"
    getUrlEncoded(encodeURI(encodeURI("https://example.com/media/Screenshot27 UI Home.jpg")))
    //"https://example.com/media/Screenshot27%20UI%20Home.jpg"
    getUrlEncoded(decodeURI("https://example.com/media/Screenshot27 UI Home.jpg"))
    //"https://example.com/media/Screenshot27%20UI%20Home.jpg"
    getUrlEncoded(decodeURI(decodeURI("https://example.com/media/Screenshot27 UI Home.jpg")))
    //"https://example.com/media/Screenshot27%20UI%20Home.jpg"
    

提交回复
热议问题