chshPay/utils/utils.js

58 lines
1.8 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.

/*
* @LastEditors: whitechiina 1293616053@qq.com
* @LastEditTime: 2025-07-31 13:42:48
*/
/**
* 获取URL参数工具函数
* @param {string|array} keys - 要获取的参数名,可以是字符串或数组
* @param {any} defaultValue - 当参数不存在时的默认值
* @returns {any} 返回参数值或参数对象
*/
const getUrlParam = function(keys, defaultValue = undefined) {
// 获取原始查询字符串(包含开头的'?'
let queryString = window.location.search;
// 预处理:将第一个问号后的所有问号替换为'&'
if (queryString.includes('?')) {
// 移除开头的'?',然后处理多个问号
let queryWithoutQuestion = queryString.substring(1);
// 将多个问号替换为&
queryWithoutQuestion = queryWithoutQuestion.replace(/\?/g, '&');
queryString = '?' + queryWithoutQuestion;
}
// 解析处理后的查询字符串
const params = new URLSearchParams(queryString);
// 1. 未传入keys返回全部参数组成的对象
if (!keys) {
const result = {};
for (const [key, value] of params.entries()) {
result[key] = decodeURIComponent(value);
}
return result;
}
// 2. 传入数组:返回包含这些参数的对象
if (Array.isArray(keys)) {
return keys.reduce((result, key) => {
result[key] = params.has(key)
? decodeURIComponent(params.get(key))
: defaultValue;
return result;
}, {});
}
// 3. 传入字符串:返回单个参数值
if (typeof keys === 'string') {
return params.has(keys)
? decodeURIComponent(params.get(keys))
: defaultValue;
}
// 4. 无效keys类型返回默认值
return defaultValue;
}
export default getUrlParam;