URL 对象简单使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style></style>
</head>
<body>
<script>
// 构造函数:参数可以是URL字符串,也可以是location对象
var url = new URL(
"http://user:passwd@www.example.com:4097/path/a.html?x=111#part1"
);
// 获取参数
var params = url.searchParams;
console.log(params.get("x")); // 111
// 一些属性
// 1. 返回整个 URL
console.log(url.href); // "http://user:passwd@www.example.com:4097/path/a.html?x=111#part1"
// 2. 返回协议
console.log(url.protocol); // http:
// 3. 返回域名
console.log(url.hostname); // www.example.com
// 4. 返回域名与端口
console.log(url.host); // www.example.com:4097
// 5. 返回端口
console.log(url.port); // 4097
// 6. 返回协议、域名和端口
console.log(url.origin); // http://www.example.com:4097
// 7. 返回路径
console.log(url.pathname); // /path/a.html
// 8. 返回查询字符串
console.log(url.search); // ?x=111
// 9. 返回片段识别符
console.log(url.hash); // #part1
// 10. 返回域名前面的密码
console.log(url.password); // passwd
// 11. 返回域名前面的用户名
console.log(url.username); // user
</script>
</body>
</html>