JS URL对象

本文详细介绍了URL对象在JavaScript中的使用,包括通过构造函数创建URL实例,以及如何访问和操作URL的各种属性,如协议、域名、端口、路径、查询参数和片段标识符等。示例代码演示了如何获取和解析URL的不同部分,对于理解和操作网页URL非常有帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值