Differences and considerations of various encoding and decoding functions in JavaScript _ javascript skills

Source: Internet
Author: User
The difference between encodeURI, encodeURIComponent and escape in JavaScript and the URL encoding of the string to be submitted when you use JS to submit data, especially in Chinese. There are several URL encoding methods for strings in JS: encodeURI, encodeURIComponent, and escape. In many of the code I see, the escape function is the most used, but this function is not recommended. Let's take a look at these functions:
  
EncodeURI: URL encoding of the specified string, excluding the key characters in: #/\=.
  
EncodeURIComponent: encode the characters in the string, including special characters in the URL.
  
Escape: This is a function in earlier versions of JS. This function has some problems when handling unicode characters.
The Code is as follows:

The Code is as follows:


Var url = "http://www.abc.com? Q = aa & amp; B = haha ";
Var encodedUrl = encodeURI (url );
Alert (encodedUrl); // output: http://www.abc.com? Q = aa & B = % E5 % 91% B5 % E5 % 91% B5
EncodedUrl = encodeURIComponent (url );
Alert (encodedUrl); // output: http % 3A % 2F % 2Fwww.abc.com % 3Fq % 3Daa % 26b % 3D % E5 % 91% B5 % E5 % 91% B5
Alert (escape (url); // output: http % 3A // www.abc.com % 3Fq % 3Daa % 26b % 3D % u5475 % u5475


As shown above, when processing Chinese characters in the escape function, it will be converted to % uxxxx. Obviously, this is different from the URL encoding format, and the encodeURIComponent function encoding is the most thorough, if there is no special need, the encodeURIComponent function is quite common. Of course, it won't be a problem if we use escape. Maybe your server language can be parsed normally, however, this function is not very standard when handling unicode characters. Therefore, we recommend that you use encodeURIComponent and decodeURIComponent to encode and decode the strings.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.