When are you supposed to use escape instead of encodeURI / encodeURIComponent?

前端 未结 15 1162
栀梦
栀梦 2020-11-21 07:39

When encoding a query string to be sent to a web server - when do you use escape() and when do you use encodeURI() or encodeURIComponent()

15条回答
  •  暖寄归人
    2020-11-21 07:52

    For the purpose of encoding javascript has given three inbuilt functions -

    1. escape() - does not encode @*/+ This method is deprecated after the ECMA 3 so it should be avoided.

    2. encodeURI() - does not encode ~!@#$&*()=:/,;?+' It assumes that the URI is a complete URI, so does not encode reserved characters that have special meaning in the URI. This method is used when the intent is to convert the complete URL instead of some special segment of URL. Example - encodeURI('http://stackoverflow.com'); will give - http://stackoverflow.com

    3. encodeURIComponent() - does not encode - _ . ! ~ * ' ( ) This function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. This method should be used to convert a component of URL. For instance some user input needs to be appended Example - encodeURIComponent('http://stackoverflow.com'); will give - http%3A%2F%2Fstackoverflow.com

    All this encoding is performed in UTF 8 i.e the characters will be converted in UTF-8 format.

    encodeURIComponent differ from encodeURI in that it encode reserved characters and Number sign # of encodeURI

提交回复
热议问题