chshPay/utils/urlUtils.js

78 lines
2.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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"