SoFunction
Updated on 2025-03-03

Comparison of several URL encoding methods in Javascript

There are several ways to encode URL strings in javascript: escape(), encodeURI(), and encodeURIComponent(). The roles of these encodings vary.

escape() method:

Use the ISO Latin character set to encode the specified string. All space characters, punctuation marks, special characters, and other non-ASCII characters will be converted into %xx character encoding (xx is equal to the hexadecimal number of the character encoded in the character set table). For example, the corresponding encoding of the space character is %20.

Characters that will not be encoded by this method: @ * / +

encodeURI() method:

Convert URI strings into escape format strings in UTF-8 encoding format.

Characters that will not be encoded by this method:! @ # $& * ( ) = : / ; ? + '

encodeURIComponent() method:

Convert the URI string into a string in escape format using UTF-8 encoding format. Compared to encodeURI(), this method will encode more characters, such as / and other characters. Therefore, if the string contains several parts of the URI, this method cannot be used to encode it, otherwise the URL will display an error after the / character is encoded.

Characters that will not be encoded by this method:! * ( ) '

Therefore, for Chinese strings, if you do not want to convert the string encoding format into UTF-8 format (for example, when the charset of the original page and the target page are the same), you only need to use escape. If your page is GB2312 or other encoding, and the page that accepts parameters is UTF-8 encoding, you must use encodeURI or encodeURIComponent.

In addition, encodeURI/encodeURIComponent was introduced after javascript 1.5, while escape was available in javascript 1.0 version.