You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// https://example.com/?name=Jonathan&age=18constparams=newURLSearchParams(document.location.search.substring(1))constname=params.get('name')// is the string "Jonathan"constage=parseInt(params.get('age'),10)// is the number 18
The end.
The text was updated successfully, but these errors were encountered:
前面会介绍一些乱七八糟的东西,请忍耐一下。
URI、URL、URN
提到这三个货,循例丢一张表出来,麻烦用余光一扫而过就算了。
网上充斥着类似上面表格中的名词解释,还有诸如以下的言论:
说真的,这些解释说了跟没说一样,我相信 99% 的人都知道但没用。还记得此前写过一篇文章介绍三者的定义及区别,现在再回头看感觉简直是浪费时间了。
以下这句话,从某乎看到的,我觉得简单明了:
因此,在 99.9% 的情况下,我们看到的 URI 全都是 URL,没必要理会 URN 了。而我们在浏览器中输入的 Web 地址,指的就是 URL(Identifying resources on the Web)。
URL
网址字符串是包含多个有意义组件的结构化字符串。 下面提供了 WHATWG 和 旧版 API 之间的比较。 在网址
'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'
上方显示的是由旧版url.parse()
返回的对象的属性。 下方则是 WHATWGURL
对象的属性。图中
""
行中的所有空格都应被忽略。它们纯粹是为了格式化。对于浏览器(前端)而言,注意几点:
origin
属性包括protocol
和host
,但不包括username
或password
。username
或password
虽然一些浏览器可能仍然支持它,但它可能已经从相关的 Web 标准中删除,可能正在被删除,或者可能只是为了兼容性目的而保留。因此,我们来简化一下:
三、获取 URL 参数
前面铺垫了那么多,其实本文的话题是获取 URL 上的参数,不废话了。
参数通常存在于
window.location.search
和window.location.hash
上,考虑一些特殊情况就好了:删掉注释部分,如下:
已收录在 toFrankie/javascript-utils,里面还有其他一些实用的方法哦!
更新(2023.02.26)
都 2023 年了,可以考虑使用 URLSearchParams 了。
The end.
The text was updated successfully, but these errors were encountered: