import qs from 'query-string';
/**
* 将 PascalCase/camelCase 转为短横线风格
* 例: MyDeviceName → my-device-name
*/
export function toKebabCase(str: string): string {
return str
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
.replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
.toLowerCase();
}
/**
* 将后端返回的菜单 URL 路径转换为短横线风格
* 示例:
* /IoT/Device/Product → /iot/device/product
* /EMS/EnergyReport → /ems/energy-report
*
* @param url 后端返回的原始 URL
* @returns 短横线风格的 URL
*/
export function normalizeMenuUrl(url: string): string {
if (!url || typeof url !== 'string') return url;
// 分离路径和查询参数
const [path, query] = url.split('?');
// 转换路径段为短横线风格
const normalizedPath = path
.split('/')
.filter(Boolean)
.map((segment) => toKebabCase(segment))
.join('/');
// 重新拼接路径(保留前导斜杠)
const result = '/' + normalizedPath;
// 附加查询参数
return query ? `${result}?${query}` : result;
}
export function isUrl(path: string) {
/* eslint no-useless-escape:0 */
const reg =
/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)(:[\d]+)?((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g;
return reg.test(path);
}
/**
* 生成带Get参数的URL
* @param {String} url 原来的url
* @param {Object} params get 参数
*/
export function generateUrlWithGetParam(url: string, params: {}) {
let newUrl = url;
if (params && Object.keys(params).length >= 1) {
const newParams = params; // filterNullValueObject
if (Object.keys(newParams).length >= 1) {
newUrl += `${url.indexOf('?') >= 0 ? '&' : '?'}${qs.stringify(newParams)}`;
}
}
return newUrl;
}
/**
* 得到get请求后面的参数部分,并去掉参数值为空的
* @param param
* @returns {String}
*/
export function getUrlParam(param: { [x: string]: any }) {
let on = true;
let result = '';
for (const item in param) {
if (on) {
on = false;
if (param[item] || param[item] === 0 || param[item] === false) {
result = `?${item}=${param[item]}`;
} else {
result = '?';
}
} else if (param[item] || param[item] === 0 || param[item] === false) {
result = `${result}&${item}=${param[item]}`;
}
}
return result;
}
|