<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
/**
* escape,encodeURI及encodeURIComponent的区别
* ----------------------------------------------
* 为什么要对URI进行编码?
* 例如URI “http://localhost:8080?name=sam&123”
*
**/
/*
为什么要对URI进行编码?
URL参数字符串中使用key=value键值对这样的形式来传参,
键值对之间以&符号分隔,但是如果value里面包含了&,服务器端会
如何解析呢。
*/
/*
node server.js
var http = require('http');
var URL = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
var params = URL.parse(req.url, true).query;
res.end(JSON.stringify(params));
}).listen(8080);
console.log('Server running on port 8080.');
*/
/*
URL="http://localhost:8080/?name=sam&123"
解析结果:{"123":"","name":"sam"}
http://localhost:8080/?name=sam%26123
解析结果:{"name":"sam&123"}
经过编码后的URL解析结果是我们想要的。
*/
/*
escape 对转义字符串或者普通字符串进行编码
ECMAScript v3 反对使用该方法,应用使用 decodeURI() 和 decodeURIComponent() 替代它。
*/
console.log(escape("\n"));
//%0A
console.log(escape("abc"));
//abc
/*
unescape 解码
*/
console.log(unescape("%0A"));
//换行
console.log(unescape("abc"));
//abc
/*
encodeURI
函数是不会进行转义的:;/?:@&=+$,#
提示:如果 URI 组件中含有分隔符,比如 ? 和 #,则应当使用 encodeURIComponent() 方法分别对各组件进行编码。
*/
console.log(encodeURI("http://www.w3school.com.cn"));
//http://www.w3school.com.cn
console.log(encodeURI("http://www.w3school.com.cn/My first/"));
//http://www.w3school.com.cn/My%20first/
console.log(encodeURI("http://www.w3school.com.cn?name=sam"));
//http://www.w3school.com.cn?name=sam
/*
encodeURIComponent
函数将转义用于分隔URI各个部分的标点符号。
*/
console.log(encodeURIComponent("http://www.w3school.com.cn"));
//http%3A%2F%2Fwww.w3school.com.cn
console.log(encodeURIComponent("sam&123"));
//sam%26123
</script>
</body>
</html>
网友评论