You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

24 lines
677 B

/**
* 将路由路径转换为正则表达式,支持 :
* - `:id` 匹配单个路径段
* - `:id+` 匹配多个路径段
* - `:id?` 可选
*/
export function pathToRegexp(pattern: string): RegExp {
// 只匹配 :param 部分(到下一个 / 或字符串结尾),不包括后续路径段
const escaped = pattern.replace(/:[^/]+(\?)?/g, (match) => {
if (match.endsWith("?")) {
return "([^/]*)";
}
return "([^/]+)";
});
return new RegExp(`^${escaped}$`);
}
export function normalizePath(path: string) {
const trimmed = path.trim();
if (!trimmed) {
return "/";
}
return trimmed.length > 1 ? trimmed.replace(/\/+$/, "") : trimmed;
}