前端获取路径参数中文乱码

前端获取路径参数中文乱码

1
2
3
4
5
6
7
8
9
//获取路径参数公共方法
getUrlParams(name: string) {
const search = window.location.search.substr(1) || window.location.hash.split('?')[1];
if (!search) return '';
let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
let r = search.match(reg);
if (r != null) return unescape(r[2]);
return null;
}

浏览器访问 : localhost:8989/index.html?projectId=123&type=1&storeId=222&storeName=瑞幸
获取到的参数值

1
2
3
4
this.getUrlParams('projectId'); //123
this.getUrlParams('type'); //1
this.getUrlParams('storeId'); //222
this.getUrlParams('storeName'); //ç 幸

查询mdn的网站, 上面显示
备注: 不要使用unescape去解码 URLS,使用decodeURI或decodeURIComponent替代
所以就使用decodeURL替换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 获取链接参数值
getUrlParams(name: string) {
const search =
window.location.search.substr(1) ||
window.location.hash.split('?')[1];
if (!search) return '';
let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
let r = search.match(reg);
if (r != null) return decodeURI(r[2]);
return null;
},
//?projectId=123&type=1&storeId=222&storeName=瑞幸
this.getUrlParams('projectId'); //123
this.getUrlParams('type'); //1
this.getUrlParams('storeId'); //222
this.getUrlParams('storeName'); //瑞幸