url转对象:new URL(‘https://www.yuque.com/kylethanas/share/ccln9z‘)

    获取当前url:document.URL

    增加删除query参数

    1. import qs from 'qs';
    2. import { omit } from 'lodash';
    3. interface QueryDict {
    4. [key: string]: any;
    5. }
    6. /**
    7. * 增加链接参数
    8. *
    9. * @param {string} href 原始链接
    10. * @param {string[]} keys 剔除字段
    11. * @return {string} 新链接
    12. */
    13. export const injectQuery = (href: string, queries: QueryDict): string => {
    14. const current = document.createElement('a');
    15. current.href = href;
    16. const { pathname, origin, search } = current;
    17. const parsed = qs.parse(search, { ignoreQueryPrefix: true });
    18. const query = { ...parsed, ...queries };
    19. if (Object.keys(query).length === 0) {
    20. return `${origin}${pathname}`;
    21. }
    22. return `${origin}${pathname}?${qs.stringify(query)}`;
    23. };
    24. /**
    25. * 删除链接参数
    26. *
    27. * @param {string} href 原始链接
    28. * @param {string[]} keys 剔除字段
    29. * @return {string} 新链接
    30. */
    31. export const omitQuery = (href: string, keys: string[]): string => {
    32. const current = document.createElement('a');
    33. current.href = href;
    34. const { pathname, origin, search } = current;
    35. const parsed = qs.parse(search, { ignoreQueryPrefix: true });
    36. const query = omit(parsed, keys);
    37. if (Object.keys(query).length === 0) {
    38. return `${origin}${pathname}`;
    39. }
    40. return `${origin}${pathname}?${qs.stringify(query)}`;
    41. };