Home > Web Front-end > JS Tutorial > body text

Guide to several ways to encode strings in JS_javascript skills

WBOY
Release: 2016-05-16 15:59:15
Original
1189 people have browsed it

Function Description
encodeURI() encodes the string into URI
encodeURIComponent() encodes a string into a URI component
escape() encodes a string

The above is to query the data from w3school. So what is the difference between the three? Please allow me to test it.

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

Copy code The code is as follows:

http://localhost:8080/Product/index?id=123&attr=456&area=China
http://localhost:8080/Product/index?id=123&attr=456&area=China
http://localhost:8080/Product/index?id=123&attr=456&area=%u4E2D%u56FD

As you can see,

encodeURI will not encode the characters used for segmentation in uri such as:/?&;

encodeURIComponent will.

Observing escape, we found that :?& was transcoded, but / was not. The w3school explanation is that the escape function will treat all characters except letters, numbers and symbols (* @ - _ . /) in the ascii code. Encode.

In addition, we can see that the result after escape encodes the Chinese character "China" is different from the first two. W3SCHOOL also recommends not using this method and using the first two instead.

The above is the entire content of this article. I hope it will be helpful to everyone learning javascript.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template