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

后端 未结 5 932
误落风尘
误落风尘 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:37

    Thanks for @mika for great answer. Maybe just one improvement since unescape function is considered as deprecated:

    declare function unescape(s: string): string;
    
    
    decodeURItoString(str): string {
    
     var resp = str;
    
     try {
        resp = decodeURI(str);
     } catch (e) {
        console.log('ERROR: Can not decodeURI string!');
    
        if ( (unescape != null) && (unescape instanceof Function) ) {
            resp = unescape(str);
        }
     }
    
    return resp;
    

    }

提交回复
热议问题