js:URL、URLSearchParams解析当前页面url和查询参数
发布日期:2021-07-01 06:11:28 浏览次数:2 分类:技术文章

本文共 1340 字,大约阅读时间需要 4 分钟。

假设当前页面的url是

https://www.baidu.com/index.html?query=Tom#app

获取当前URL对象

window.location

打印出的结果

hash: '',host: 'www.baidu.com',hostname: 'www.baidu.com',href: 'https://www.baidu.com/index.html?query=Tom#app',origin: 'https://www.baidu.com',pathname: '/index.html',port: '',protocol: 'https:',search: '?query=Tom',reload()replace()

创建 URL 对象

var url = new URL("https://www.baidu.com/index.html?query=Tom#app");console.log(url);
URL {  href: 'https://www.baidu.com/index.html?query=Tom#app',  origin: 'https://www.baidu.com',  protocol: 'https:',  username: '',  password: '',  host: 'www.baidu.com',  hostname: 'www.baidu.com',  port: '',  pathname: '/index.html',  search: '?query=Tom',  searchParams: URLSearchParams { 'query' => 'Tom' },  hash: '#app' }  协议 protocol主机名 hostname端口 port主机 host来源 origin)文件名 pathname锚点 hash查询参数 search

使用 URLSearchParams 解析查询参数

var searchParams = new URLSearchParams("query=Tom");console.log(searchParams);// URLSearchParams { 'query' => 'Tom' }console.log(searchParams.get("query"));// Tom

使用实例

1、Node端示例

let href = "https://www.baidu.com/index.html?name=Tom";let url = new URL(href);let name = url.searchParams.get("name");console.log(name);// Tom

2、 浏览器下示例

// https://www.baidu.com/index.html?name=Tomlet url = new URL(window.location.href);let name = url.searchParams.get("name");console.log(name);// Tom

参考

转载地址:https://pengshiyu.blog.csdn.net/article/details/106827674 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:百度统计:页面代码安装状态:代码未生效
下一篇:JS:crypto-js实现AES加密解密

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月18日 16时10分54秒