假设当前页面的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()
使用 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
参考