将对象添加到URL中作为参数
const params2Url = (uri, params) => {
const paramsArray = [];
Object.keys(params).forEach(
(key) => params[key] && paramsArray.push(`${key}=${params[key]}`)
);
if (uri.search(/\?/) === -1) {
uri += `?${paramsArray.join("&")}`;
} else {
uri += `&${paramsArray.join("&")}`;
}
return uri;
};
let params = {
keyword: "t",
page: 1,
size: 2,
};
params2Url('/datasource/check/p', params)
提取出url 里的参数并转成对象
function getUrlParams(url){
let reg = /([^?&=]+)=([^?&=]+)/g
let obj = { }
url.replace(reg, function(){
obj[arguments[1]] = arguments[2]
})
// 或者
const search = window.location.search
search.replace(/([^&=?]+)=([^&]+)/g, (m, $1, $2)=>{obj[$1] = decodeURIComponent($2)})
return obj
}
let url = 'https://www.junjin.cn?a=1&b=2'
console.log(getUrlParams(url)) // { a: 1, b: 2 }