平时写前端逻辑,很多时候会遇到,需要取url中参数的情况,这个时候我们可能会取url后面的参数一顿匹配。
1、通过serach取到参数
// http://127.0.0.1/index?id=999&name=888
const {serach = '',href}=window.location;
// serach取到的值就是 ?id=999&name=888
// href为http://127.0.0.1/index?id=999&name=888
2、匹配取参数
平时普通的办法,就是取到的值通过正则匹配到id和name。如下。
方法一
const getvl=(name) => {
const reg = new RegExp("(^|\\?|&)"+ name +"=([^&]*)(\\s|&|$)", "i");
if (reg.test(location.search)){
return unescape(RegExp.$2.replace(/\+/g, " "));
}
return "";
};
const code = getvl("name");
方法二
interface UrlParamsProps {
key?: string;
href?: string;
}
/**
* 获取url中?拼接数据
* key 为希望获取值的键,默认返回整个对象
* href 为希望处理的url地址,默认使用window.location.href
* @param params UrlParamsProps
*/
export function urlParams(params: UrlParamsProps) {
const queryStr = params.href
? params.href.split('?')
: window.location.href.split('?');
if (queryStr[1]) {
const paramsObj = queryStr[1].split('&');
const obj: any = {};
paramsObj.forEach(item => {
const _itme = item.split('=');
obj[_itme[0]] = decodeURIComponent(_itme[1]);
});
return params.key ? obj[params.key] : obj;
}
}
3、利用URLSearchParams。
如下,两行代码就可以直接取出来参数了,要是不用考虑兼容IE的话,使用起来很方便呢。还有一些其他的API方法,如get\sort\has等,这些方法的兼容性就更差了。
const query = new URLSearchParams('?id=12313&aa=90laa');
query.get('id');