js实现路由match
js实现路由匹配的方法
基于字符串路径的简单匹配
使用字符串比较或正则表达式实现基础路由匹配,适合简单场景。
const routes = {
'/home': 'Home Page',
'/about': 'About Page'
};
function matchRoute(path) {
return routes[path] || '404 Not Found';
}
动态参数路由匹配
通过正则表达式提取路径中的动态参数,实现灵活的路由匹配。
const dynamicRoutes = [
{ pattern: /^\/user\/(\w+)$/, handler: (id) => `User ${id}` },
{ pattern: /^\/post\/(\d+)$/, handler: (id) => `Post ${id}` }
];
function matchDynamicRoute(path) {
for (const route of dynamicRoutes) {
const match = path.match(route.pattern);
if (match) return route.handler(match[1]);
}
return '404 Not Found';
}
路由前缀匹配
处理嵌套路由或路由前缀时,使用字符串的startsWith方法或正则表达式。

const prefixRoutes = [
{ prefix: '/admin', handler: 'Admin Area' },
{ prefix: '/api', handler: 'API Endpoint' }
];
function matchPrefixRoute(path) {
const route = prefixRoutes.find(r => path.startsWith(r.prefix));
return route ? route.handler : '404 Not Found';
}
通配符路由匹配
实现类似*的通配符匹配,处理未定义的路由或兜底逻辑。
const wildcardRoutes = {
'/dashboard/*': 'Dashboard Subroute',
'/*': 'Fallback Page'
};
function matchWildcardRoute(path) {
for (const [pattern, handler] of Object.entries(wildcardRoutes)) {
const regex = new RegExp('^' + pattern.replace('*', '.*') + '$');
if (regex.test(path)) return handler;
}
return '404 Not Found';
}
使用URL对象解析
利用浏览器内置的URL API进行更精确的路由解析和参数提取。

function matchURLRoute(urlString) {
const url = new URL(urlString, window.location.origin);
const path = url.pathname;
const params = Object.fromEntries(url.searchParams.entries());
if (path === '/search') return `Search for: ${params.q}`;
return '404 Not Found';
}
路由优先级处理
当存在多个匹配路由时,通过优先级排序确定最终匹配结果。
const priorityRoutes = [
{ path: '/user/exact', priority: 2, handler: 'Exact User' },
{ path: '/user/*', priority: 1, handler: 'Generic User' }
];
function matchPriorityRoute(path) {
const matched = priorityRoutes.filter(r =>
new RegExp('^' + r.path.replace('*', '.*') + '$').test(path)
).sort((a, b) => b.priority - a.priority);
return matched[0]?.handler || '404 Not Found';
}
哈希路由实现
针对单页应用的哈希路由方案,监听hashchange事件进行路由匹配。
window.addEventListener('hashchange', () => {
const hash = window.location.hash.slice(1) || '/';
const handler = matchRoute(hash); // 使用前述任一匹配方法
renderContent(handler);
});
路由参数对象化
将匹配的路由参数封装为对象,便于后续处理和使用。
function matchParams(path) {
const paramPattern = /\/:(\w+)/g;
const pathPattern = path.replace(paramPattern, '/(\\w+)');
return {
regex: new RegExp(`^${pathPattern}$`),
keys: [...path.matchAll(paramPattern)].map(m => m[1])
};
}
function parseParams(path, {regex, keys}) {
const match = path.match(regex);
if (!match) return null;
return keys.reduce((params, key, i) => {
params[key] = match[i+1];
return params;
}, {});
}






