const UrlUtils = { /** * 清理URL(合并多余的?,规范参数分隔符) * @param {string} url - 原始URL * @returns {string} 清理后的URL */ clean: function(url) { let cleanUrl = url.replace(/\?+/g, '?'); const firstQuestionMarkIndex = cleanUrl.indexOf('?'); if (firstQuestionMarkIndex !== -1) { const beforeParams = cleanUrl.substring(0, firstQuestionMarkIndex + 1); const afterParams = cleanUrl.substring(firstQuestionMarkIndex + 1).replace(/\?/g, '&'); cleanUrl = beforeParams + afterParams; } return cleanUrl; }, /** * 保留URL中指定的参数(默认只保留merchant_id) * @param {string} url - 原始URL * @param {string[]} [paramsToKeep=['merchant_id']] - 需要保留的参数名数组 * @returns {string} 简化后的URL */ keepParams: function(url, paramsToKeep = ['merchant_id']) { // 先清理URL const cleanedUrl = this.clean(url); try { const urlObj = new URL(cleanedUrl); const newSearchParams = new URLSearchParams(); // 遍历原始参数,只保留需要的 urlObj.searchParams.forEach((value, key) => { if (paramsToKeep.includes(key)) { newSearchParams.append(key, value); } }); // 重建URL urlObj.search = newSearchParams.toString(); return urlObj.toString(); } catch (e) { // 如果URL解析失败(如缺少协议),回退到字符串处理 const [basePart, queryPart] = cleanedUrl.split('?'); if (!queryPart) return basePart; const keptParams = queryPart.split('&').filter(param => { const [key] = param.split('='); return paramsToKeep.includes(key); }); return keptParams.length > 0 ? `${basePart}?${keptParams.join('&')}` : basePart; } } }; export default UrlUtils // // 使用示例 // const dirtyUrl = "http://10.210.254.149:8081/h5_pay/??merchant_id=1&token=xxx&expires_time=123??is_all_api=1"; // // 1. 只清理URL // console.log(UrlUtils.clean(dirtyUrl)); // // 输出: "http://10.210.254.149:8081/h5_pay/?merchant_id=1&token=xxx&expires_time=123&is_all_api=1" // // 2. 清理并只保留merchant_id // console.log(UrlUtils.keepParams(dirtyUrl)); // // 输出: "http://10.210.254.149:8081/h5_pay/?merchant_id=1" // // 3. 清理并保留多个参数 // console.log(UrlUtils.keepParams(dirtyUrl, ['merchant_id', 'expires_time'])); // // 输出: "http://10.210.254.149:8081/h5_pay/?merchant_id=1&expires_time=123"