url转成obj或者obj转成url的方法
1、url转成obj
function urlToObj(url) {
if (typeof url !== 'string') return '请传入正确的参数类型'
const urlArr = url.split('?');
let obj = {};
let params = {};
if (urlArr?.length) {
urlArr.forEach((item, index) => {
if (!index) return obj.path = item;
const itemArr = item?.split('&');
itemArr.forEach(it => {
if (it) {
const itArr = it.split('=');
if (itArr[0]) params[itArr[0]] = itArr[1];
}
})
})
}
obj.query = params;
return obj
}
使用:
const a = urlToObj('http:baidu.com?age=1&sex=nan')
console.log(a);//{path: 'http:baidu.com', query: {…}}
2、obj转成url
function objToUrl(url) {
let newUrl = '';
if (url?.path) newUrl = url.path + '?';
if (url?.query) {
for (let key in url?.query) {
newUrl += `${key}=${url?.query[key]}&`
}
}
return newUrl.slice(0, newUrl?.length - 1)
}
使用:
const b = objToUrl({
path: 'http:baidu.com',
query: {
age: 11,
name: '小花'
}
})
console.log(b)//http:baidu.com?age=11&name=小花