现在许多的主流网站都将’#'大规模用于重要URL中,我们通过正则表达式和window.location.search
获取参数已经行不通了。
一.'#'号是什么
-
#代表网页中的一个位置。其后面的字符,就是该位置的标识符。
-
#是用来指导浏览器动作的,对服务器端完全无用。所以,HTTP请求中不包括#。
-
在第一个#后面出现的任何字符,都会被浏览器解读为位置标识符。这意味着,这些字符都不会被发送到服务器端。
-
单单改变#后的部分,浏览器只会滚动到相应位置,不会重新加载网页。
-
每一次改变#后的部分,都会在浏览器的访问历史中增加一个记录,使用"后退"按钮,就可以回到上一个位置。
二.如何获取#号后的字符串
-
window.location.search
:获取当前URL的’?'号开始的字符串 -
window.location.hash
:获取当前URL的’#'后面的字符串
三.实现
1.获取链接后的参数(不带#号)
getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURIComponent(r[2]);
return null;
}
console.log('name is ',getQueryString('name'))
2.获取链接后的参数(带#号)
getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
if(window.location.hash.indexOf("?") < 0){
return null;
}
let r = window.location.hash.split("?")[1].match(reg);
if (r != null) return decodeURIComponent(r[2]);
return null;
}
console.log('name is ',getQueryString('name'))
3.使用npm:fetch-url-params
npm install -S fetch-url-params
import fetchUrlParams from 'fetch-url-params'
let params = fetchParams(url)
console.log(params)
// 获取完整的地址栏参数,包括hash部分
// 如:https://www.npmjs.com/search?q=fetch-url-params/#/index?id=1
// 结果:{ q: 'fetch-url-params', id: '1' }
评论区