JavaScript获取url的各方法汇总

JavaScript获取url中基本信息的各种方法

一、背景

获取url的基本信息在前后端都需要使用,举个例子,当用户未注册,需要访问某个地址的

以我的博客的某篇文章地址为例:

http://syzzjw.cn/notes/user_articles_list/syz_c_s_m/

二、代码

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

let test = window.location.href;

结果: http://syzzjw.cn/notes/user_articles_list/syz_c_s_m/

2、window.location.protocol(设置或获取 URL 的协议部分)

let test = window.location.protocol;

结果:http:

3、window.location.host(设置或获取 URL 的主机部分)

let test = window.location.host;

结果:syzzjw.cn

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

let test = window.location.port;

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

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

let test = window.location.pathname;

结果:syzzjw.cn/notes/user_articles_list/syz_c_s_m/

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

let test = window.location.search;

结果:空字符串,因为我的没有?及以后的参数,举个其他例子:http://syzzjw.cn/search/?q=%E5%A4%A9%E7%A7%80

那么test结果过就是?q=%E5%A4%A9%E7%A7%80(经过base64编码的)