操作URL的常用函数

说明:建议打开浏览器的一个页面,用开发者工具去测试不同的函数所返回的结果

1.window.location.href(设置或获取整个 URL 为字符串)

演示:console.log(window.location.href)

结果:http://www.jianshu.com/search?q=123&page=1&type=note

2.window.location.protocol(设置或获取 URL 的协议部分)
演示:console.log(window.location.protocol)

结果:http:

3、window.location.host(设置或获取 URL 的主机部分)
演示:console.log(window.location.host)

结果:www.jianshu.com

4、window.location.port(设置或获取与 URL 关联的端口号码)
演示:console.log(window.location.port)

结果:8089(如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符)

5、window.location.pathname(设置或获取与 URL 的路径部分(就是文件地址))
演示:console.log(window.location.pathname)

结果:/search

6、window.location.search(设置或获取 href 属性中跟在问号后面的部分)
演示:console.log(window.location.search)

结果:?q=123&page=1&type=note

7、window.location.hash(设置或获取 href 属性中在井号“#”后面的分段)
演示:console.log(window.location.hash)

结果:空字符(因为url中没有)

posted @ 2023-08-17 15:06  尤念  阅读(28)  评论(0编辑  收藏  举报