删除url某个参数:
/**
* @description 删除地址里的query参数
* @param {String} url 要删除参数的地址
* @param {String} name 参数key
* @return {String} 新的地址
*/
const deleteQueryString = (url, name) => {
const reg = new RegExp('(|&)' + name + '=([^&/#]*)')
const str = url.match(reg)
if (str && str[0]) {
const newUrl = url.replace(str[0], '')
return newUrl
}
return url
}
console.log(deleteQueryString('https://www.test.com?productId=1048&proxyId=1', 'productId'));
//输出 https://www.test.com/?&proxyId=1
获取url:
//url: https://www.test.com?productId=1&proxyId=1 使用
const getQueryObject = (url) => {
let str = url.replace("?", "&").split("&");
let query = {};
str.forEach((item) => {
if (item.includes('=')) {
let queryArray = item.split("=");
query[queryArray[0]] = queryArray[1];
}
});
return query;
};
console.log(getQueryObject('https://www.test.com?productId=1048&proxyId=1'));
//输出 {"productId": "1048","proxyId": "1"}
//window.location.hash 使用
export const hashRouteQuery= (path) => {
let location = window.location.hash || path
let str = location.replace('?', '&').split('&');
let query = {};
str.forEach((element) => {
let queryArray = element.split('=');
query[queryArray[0]] = queryArray[1];
});
return query;
};