url转对象:new URL(‘https://www.yuque.com/kylethanas/share/ccln9z‘)
获取当前url:document.URL
增加删除query参数
import qs from 'qs';
import { omit } from 'lodash';
interface QueryDict {
[key: string]: any;
}
/**
* 增加链接参数
*
* @param {string} href 原始链接
* @param {string[]} keys 剔除字段
* @return {string} 新链接
*/
export const injectQuery = (href: string, queries: QueryDict): string => {
const current = document.createElement('a');
current.href = href;
const { pathname, origin, search } = current;
const parsed = qs.parse(search, { ignoreQueryPrefix: true });
const query = { ...parsed, ...queries };
if (Object.keys(query).length === 0) {
return `${origin}${pathname}`;
}
return `${origin}${pathname}?${qs.stringify(query)}`;
};
/**
* 删除链接参数
*
* @param {string} href 原始链接
* @param {string[]} keys 剔除字段
* @return {string} 新链接
*/
export const omitQuery = (href: string, keys: string[]): string => {
const current = document.createElement('a');
current.href = href;
const { pathname, origin, search } = current;
const parsed = qs.parse(search, { ignoreQueryPrefix: true });
const query = omit(parsed, keys);
if (Object.keys(query).length === 0) {
return `${origin}${pathname}`;
}
return `${origin}${pathname}?${qs.stringify(query)}`;
};