Comparison and analysis of JavaScript string encoding function escape, encodeURI, encodeURIComponent
today, in a project that originally used AJAX to automatically reduce the selection content, when the input name was entered, if the input had a special character.A Mp; the content of the selection will not change, that is to say the content of the input is in the.Amp; the content behind will be truncated, and it is found that when the client uses AJAX to send the data to the client, the data content is not encoded by the URL and is sent directly on the URL address, because the test was at the time. Considering the name of the company, there is no special character or serious consideration. When the special character.Amp is entered, the content will be truncated. The solution is to URL the content to be sent, and you can use the following JavaScript string encoding functions:
escape (), encodeURI (), and encodeURIComponent (). The functions of these codes are different. The
escape () method:
encodes the specified string using the ISO Latin character set. All of the spaces, punctuation, special characters, and other non - ASCII characters will be converted into%xx - format character encoding (XX equals the coded 16 - digit number of the character in the character set table). For example, the code corresponding to the space character is.
characters that will not be encoded by this method: @ * /
encodeURI () method:
conversion of URI strings in UTF-8 coded format into escape format strings.
characters that will not be encoded by this method:! @ $.amp; * () =: /;'
encodeURIComponent () method:
convert the URI string in UTF-8 encoding format into a escape format string. Compared with encodeURI (), this method will encode more characters, such as characters. So if the string contains several parts of the URI, it can't be encoded with this method, or if the character is coded, the URL will display the error.
will not be encoded by this method: * () * ()'
so, for the Chinese string, if you do not want to convert the string encoding format into UTF-8 format (when the original page and the charset of the target page are consistent), only need to use escape. If your page is GB2312 or other encoding, and the page that accepts the parameter is UTF-8 encoded, encodeURI or encodeURIComponent should be used.
in addition, encodeURI/encodeURIComponent was introduced after javascript1.5, and escape in javascript1.0 version.