The differences and precautions of various encoding and decoding functions in JavaScript _javascript skills

Source: Internet
Author: User
When you use JS to submit data, especially in Chinese, you will often need the string to be submitted for URL encoding. There are several ways to URL-encode strings in JS, Encodeuri,encodeuricomponent, and escape. In many of the code I see, Escape is the most used function, but this function is not recommended. Let's take a look at some of these functions separately:
  
encodeURI: URL-coded for the specified string, excluding: #/\ = & key characters in these URLs.
  
encodeURIComponent: Encodes characters in a string, including special characters in the URL.
  
Escape: This is JS's earlier version of the function, which has some problems dealing with Unicode characters.
The code is as follows:
Copy Code code as follows:

var url = "http://www.abc.com?q=aa& amp;b= hehe";
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, the escape function in the processing of Chinese characters, will be converted to%uxxxx this form, obviously this and URL encoding format is not the same, and encodeuricomponent function encoding is the most thorough, if there is no special needs, encodeURIComponent This function is more commonly used, of course, maybe we use escape is not a problem, maybe your server language can also be normal parsing, but this function in the processing of Unicode characters is not very standard, so here We recommend that you use the encodeURIComponent and decodeuricomponent functions to URL-encode and decode 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.