如何在window.location中的`?`之后获取url的部分
我在 JS 中遇到了问题。window.location.href显示 URL 的完整位置。window.location.hostname显示主机名。window.location.pathname显示路径。但是code我需要使用什么来显示扩展名。
示例
网址是https://www.w3schools.com/js/tryit.asp?filename=tryjs_loc_href
我得到
window.location.href: https://www.w3schools.com/js/tryit.asp?filename=tryjs_loc_href
window.location.hostname: www.w3schools.com
window.location.pathname: /js/tryit.asp
what code? = filename=tryjs_loc_href
window.location.href: https://www.w3schools.com/js/tryit.asp?filename=tryjs_loc_href
window.location.hostname: www.w3schools.com
window.location.pathname: /js/tryit.asp
what code? = filename=tryjs_loc_href
如果你不明白请看图片
我的代码是
document.getElementById("demo").innerHTML = "The full URL of this page is:<br>" + window.location.href;
回答
使用URL searchParams或仅 location.search (此处也可在 url
const url = new URL("https://www.w3schools.com/js/tryit.asp?filename=tryjs_loc_href")
const search = url.search; // or location.search
console.log(search.slice(1)); // remove the ?
console.log(url.searchParams.get("filename")); // or get just the filename
PS:我每天都推荐MDN 而不是 w3schools