UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

65 lines (61 loc) 2.22 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * 根据传入的参数,移除原来的所有参数,根据传入的 keepParamsObj 进行重新拼接地址,以 hash 模式返回 * @param {string} url 地址 * @param {object} keepParamsObj 参数对象 * @returns 只有传入参数的地址 * @example * const url1 = formatUrlParams('http://www.test.com?a=1&b=2&c=3', { e: 5 }); // http://www.test.com/#/?e=5 * const url2 = formatUrlParams('http://www.test.com?a=1&b=2&c=3#/detail?d=4', { f: 5 }); // http://www.test.com/#/detail?f=5 */ function formatUrlParams(url, keepParamsObj, forceHistoryMode) { if (url === void 0) { url = ''; } if (keepParamsObj === void 0) { keepParamsObj = {}; } // 参数校验 var keepKeyArr = Object.keys(keepParamsObj); if (!url) { return url; } // 转换地址参数为字符串 var paramsStr = keepKeyArr.reduce(function (str, key) { var value = keepParamsObj[key]; var item = "".concat(key, "=").concat(value); if (str !== '') { return "".concat(str, "&").concat(item); } return item; }, ''); // 通过 HTMLAnchorElement 规范链接格式 var anchorElement = document.createElement('a') || {}; anchorElement.href = url; var _a = anchorElement.origin, origin = _a === void 0 ? '' : _a, _b = anchorElement.pathname, pathname = _b === void 0 ? '' : _b, _c = anchorElement.hash, hash = _c === void 0 ? '' : _c; if (!origin) { return url; } // 获取 router 的目标 path var matchRes = hash.match(/^#([^?]*)/); var routeName = matchRes === null || matchRes === void 0 ? void 0 : matchRes[1]; // 重新拼接链接,判断采用 history 或 hash 模式返回 var routerPath = ''; // hash 模式拼上 if (!forceHistoryMode) { var isHistory = url.includes('?') && !url.includes('#'); // forceHistoryMode未传的history模式,默认加上hash if (!(forceHistoryMode !== false && isHistory)) { routerPath = "#".concat(routeName || '/'); } } var formatUrl = "".concat(origin).concat(pathname).concat(routerPath, "?").concat(paramsStr); return formatUrl; } exports.formatUrlParams = formatUrlParams;