js实现路由match
路由匹配的实现方法
在JavaScript中实现路由匹配通常涉及解析URL路径并与预定义的路由规则进行比较。以下是几种常见的实现方式:
基础字符串匹配
使用简单的字符串比较来实现路由匹配:
const routes = {
'/home': 'HomePage',
'/about': 'AboutPage',
'/contact': 'ContactPage'
};
function matchRoute(path) {
return routes[path] || 'NotFoundPage';
}
动态参数匹配
实现带参数的路由匹配,使用正则表达式捕获动态部分:
const dynamicRoutes = [
{ pattern: /^\/user\/(\w+)$/, component: 'UserPage' },
{ pattern: /^\/post\/(\d+)$/, component: 'PostPage' }
];
function matchDynamicRoute(path) {
for (const route of dynamicRoutes) {
const match = path.match(route.pattern);
if (match) {
return {
component: route.component,
params: match.slice(1)
};
}
}
return { component: 'NotFoundPage' };
}
路径到正则转换
将类似Express的路由语法转换为正则表达式:
function pathToRegex(path) {
return new RegExp(
'^' + path.replace(/\//g, '\\/').replace(/:\w+/g, '([^/]+)') + '$'
);
}
const route = {
path: '/user/:id',
regex: pathToRegex('/user/:id'),
component: 'UserPage'
};
function match(path) {
const match = path.match(route.regex);
if (match) {
return {
component: route.component,
params: { id: match[1] }
};
}
return null;
}
通配符匹配
实现通配符路由匹配功能:
function matchWildcard(path, pattern) {
const regex = new RegExp(
'^' + pattern.replace(/\*/g, '.*').replace(/\//g, '\\/') + '$'
);
return regex.test(path);
}
路由优先级处理
处理多个可能匹配的路由时确定优先级:
const routes = [
{ path: '/user/:id', component: 'UserDetail' },
{ path: '/user/list', component: 'UserList' }
];
function findMatchingRoute(path) {
// 精确匹配优先
const exactMatch = routes.find(r => r.path === path);
if (exactMatch) return exactMatch;
// 参数匹配次之
return routes.find(r => {
const regex = pathToRegex(r.path);
return regex.test(path);
});
}
查询参数处理
提取URL中的查询参数:
function parseQuery(queryString) {
return queryString.split('&').reduce((acc, pair) => {
const [key, value] = pair.split('=');
if (key) acc[decodeURIComponent(key)] = decodeURIComponent(value || '');
return acc;
}, {});
}
哈希路由处理
处理基于哈希的路由:
window.addEventListener('hashchange', () => {
const path = window.location.hash.substr(1) || '/';
const matched = matchRoute(path);
renderComponent(matched.component);
});
完整路由示例
综合实现一个简单的路由系统:
class Router {
constructor() {
this.routes = [];
this.currentComponent = null;
}
addRoute(path, component) {
this.routes.push({
regex: pathToRegex(path),
component,
keys: path.match(/:\w+/g) || []
});
}
match(path) {
for (const route of this.routes) {
const match = path.match(route.regex);
if (match) {
const params = {};
route.keys.forEach((key, i) => {
params[key.substr(1)] = match[i + 1];
});
return { component: route.component, params };
}
}
return { component: 'NotFound' };
}
navigate(path) {
const { component, params } = this.match(path);
this.currentComponent = component;
this.render(params);
}
render(params) {
// 渲染逻辑
}
}
这些方法展示了从简单到复杂的路由匹配实现,可以根据项目需求选择适合的方案或组合使用多种技术。







