您当前的位置: 首页 >  ar

彭世瑜

暂无认证

  • 0浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

js:URL、URLSearchParams解析当前页面url和查询参数

彭世瑜 发布时间:2020-06-18 12:05:18 ,浏览量:0

假设当前页面的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=Tom
let url = new URL(window.location.href);
let name = url.searchParams.get("name");
console.log(name);
// Tom

参考 使用JavaScript解析URL的方法示例

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.1864s