How to detect if a string is encoded with escape() or encodeURIComponent()

后端 未结 5 1044
误落风尘
误落风尘 2020-12-31 11:48

I have a web service that receives data from various clients. Some of them sends the data encoded using escape(), while the others instead use encodeURIComponent(). Is there

5条回答
  •  余生分开走
    2020-12-31 12:32

    This won't help in the server-side, but in the client-side I have used javascript exceptions to detect if the url encoding has produced ISO Latin or UTF8 encoding.

    decodeURIComponent throws an exception on invalid UTF8 sequences.

    try {
         result = decodeURIComponent(string);
    }
    catch (e) {
         result =  unescape(string);                                       
    }
    

    For example, ISO Latin encoded umlaut 'ä' %E4 will throw an exception in Firefox, but UTF8-encoded 'ä' %C3%A4 will not.

    See Also

    • decodeURIComponent vs unescape, what is wrong with unescape?
    • Comparing escape(), encodeURI(), and encodeURIComponent()

提交回复
热议问题