JS guidelines for several ways to encode strings
- 2020-06-12 08:31:44
- OfStack
The function description
encodeURI() encodes the string URI
encodeURIComponent() encodes the string as an URI component
escape() encodes strings
Above is the query for data from w3school. So what is the difference between the three, please allow me to 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 print results are as follows:
http://localhost:8080/Product/index?id=123&attr=456&area=%E4%B8%AD%E5%9B%BD
http%3A%2F%2Flocalhost%3A8080%2FProduct%2Findex%3Fid%3D123%26attr%3D456%26area%3D%E4%B8%AD%E5%9B%BD
http%3A//localhost%3A8080/Product/index%3Fid%3D123%26attr%3D456%26area%3D%u4E2D%u56FD
As you can see,
encodeURI will not be correct :/? & And so on uri to play the role of segmentation character encoding;
encodeURIComponent will.
Observation of escape shows that :? & w3school means that the escape function encodes all characters in the ascii code other than letters, Numbers and symbols (* @ - _ +. /).
In addition, we can see that the result of escape encoding the Chinese character "China" is different from the former two. W3SCHOOL also recommends not using this method and replacing it with the first two.
Above is the whole content of this article, I hope to help you learn javascript.