How to use javascript to encode strings

Source: Internet
Author: User
In the client, to encode strings, you can use: escape (); encodeurl (); encodeURIComponent (); The following describes these methods. Function Description
EncodeURI () encodes the string into URI
EncodeURIComponent () encodes a string into a URI component.
Escape () encode the string

The above is a query of information from w3school. So what is the difference between the three? let me test it.

The Code is as follows:


Var str = "http: // localhost: 8080/Product/index? Id = 123 & attr = 456 & area = China ";
Console. log (encodeURI (str ));
Console. log (encodeURIComponent (str ));
Console. log (escape (str ));

The output is as follows:

The Code is as follows:


Http: // localhost: 8080/Product/index? Id = 123 & attr = 456 & area = % E4 % B8 % AD % E5 % 9B % BD
Http % 3A % 2F % 2 Flocalhost % 3A8080% 2 FProduct % 2 Findex % 3Fid % 3D123% 26 attr % 3D456% 26 area % 3D % E4 % B8 % AD % E5 % 9B % BD
Http % 3A // localhost % 3A8080/Product/index % 3Fid % 3D123% 26 attr % 3D456% 26 area % 3D % u4E2D % u56FD

As you can see,

EncodeURI will not :/? & Encode the characters that are separated by Uris;

EncodeURIComponent.

Observe escape and find ,:? & All are transcoded, And/No. w3school explains that the escape function performs operations on the letters, numbers, and symbols (* @-_ +) in the ascii code..

In addition, we can see that the escape encoding results for Chinese characters "China" are different from those of the previous two. We recommend that you do not use this method for W3SCHOOL, instead of the first two.

The above is all the content of this article. I hope it will be helpful for you to learn javascript.

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.