开发中经常用到解析地址query参数,常用的做法有几种:
const url = 'http://localhost?name=wcx&age=20&return_url=http://wcx.com?type=js&kk=19';
- 自己动手写匹配规则,字符串切割或者正则匹配
function getQueryObject(url) {
url = url == null ? window.location.href : url;
var search = url.slice(url.indexOf('?') + 1);
var obj = {};
var reg = /([^?&=]+)=([^&]*)/g;
search.replace(reg, (_, $1, $2) => {
obj[$1] = $2;
});
return obj;
}
getQueryObject(url)
结果:
getQueryObject {
name: 'wcx',
age: '20',
return_url: 'http://wcx.com?type=js',
kk: '19'
}
- 使用qs包解析参数 , npm i qs 安装这个包 或者直接在浏览器用script引入,这里介绍一下script使用
<script src="https://cdn.bootcdn.net/ajax/libs/qs/6.10.3/qs.js"></script>
<script>
const url =
'http://localhost?name=wcx&age=20&return_url=http://wcx.com?type=js&kk=18';
const queryString = url.slice(url.indexOf('?') + 1);
const queryObj = Qs.parse(queryString);
console.log('queryObj', JSON.stringify(queryObj));
结果:
{"name":"wcx","age":"20","return_url":"http://wcx.com?type=js","kk":"18"}
</script>
- 使用最新的URLSearchParams
const queryString = url.match(/\?.*/g)[0].replace(/\?/, '');
const queryObj = new URLSearchParams(queryString);
console.log('queryObj', queryObj); // { 'name' => 'wcx', 'age' => '20', 'return_url' => 'http://wcx.com?type=js' }
获取具体URLSearchParams中具体的某个值,可以使用
queryObj.get('name') // wcx