Several ways to encode a string in JS

Source: Internet
Author: User

Function Describe
encodeURI () Encode a string as a URI
encodeURIComponent () Encode a string as a URI component
Escape () Encode a string

The above is a query from W3school data. So what's the difference between the three, please allow me to test the test.

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 printing results are as follows:

http://localhost:8080/product/index?id=123&attr=456&area=%e4%b8%ad%e5%9b%bdhttp%3A% 2f%2flocalhost%3a8080%2fproduct%2findex%3fid%3d123%26attr%3d456%26area%3d%e4%b8%ad%e5%9b%Http%3A/ /LOCALHOST%3A8080/PRODUCT/INDEX%3FID%3D123%26ATTR%3D456%26AREA%3D%U4E2D%U56FD

Can be seen,

encodeURI does not encode the characters in the URI such as:/?&, such as the partition function;

The encodeURIComponent will.

Observing escape found that,:?& were transcoded, and/or no, W3school explained that the escape function would have letters, numbers, and symbols in ASCII codes (* @-_ +). /) to encode all characters except the

In addition, we can see that the result of escape is different from the previous two after the Chinese character encoding. W3school also recommends that you do not use the method and replace it with the previous two.

Several ways to encode a string in JS

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.