当前位置:首页 > JavaScript

js 实现pathmatcher

2026-04-05 15:07:27JavaScript

PathMatcher 实现方法

基本概念

PathMatcher 用于匹配 URL 路径或文件路径,常用于路由系统或文件系统操作。JavaScript 中可通过正则表达式或字符串处理实现路径匹配功能。

正则表达式实现

通过正则表达式匹配路径模式,支持通配符和参数提取:

function pathMatcher(pattern, path) {
  const regex = new RegExp('^' + pattern
    .replace(/\*/g, '.*')
    .replace(/\//g, '\\/')
    .replace(/:(\w+)/g, '(?<$1>[^/]+)') + '$');
  return path.match(regex);
}

// 示例用法
const result = pathMatcher('/users/:id/profile', '/users/123/profile');
console.log(result?.groups?.id); // 输出 "123"

通配符匹配

实现简单的通配符匹配功能,支持 * 匹配任意字符:

function wildcardMatch(pattern, path) {
  const regex = new RegExp(`^${pattern.split('*').map(escapeRegExp).join('.*')}$`);
  return regex.test(path);
}

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

// 示例
wildcardMatch('/api/*/detail', '/api/users/detail'); // true

路径参数解析

从路径中提取命名参数:

function extractParams(pattern, path) {
  const paramNames = [];
  const regexPattern = pattern.replace(/:(\w+)/g, (_, name) => {
    paramNames.push(name);
    return '([^/]+)';
  });

  const match = new RegExp(`^${regexPattern}$`).exec(path);
  if (!match) return null;

  return paramNames.reduce((params, name, index) => {
    params[name] = match[index + 1];
    return params;
  }, {});
}

// 使用示例
const params = extractParams('/product/:category/:id', '/product/electronics/42');
// { category: 'electronics', id: '42' }

性能优化版本

对于高频使用的场景,可预先编译匹配模式:

class PathMatcher {
  constructor(pattern) {
    this.keys = [];
    this.regex = this.compile(pattern);
  }

  compile(pattern) {
    const tokens = pattern.split('/');
    const parts = tokens.map(token => {
      if (token.startsWith(':')) {
        this.keys.push(token.slice(1));
        return '([^/]+)';
      }
      return token;
    });
    return new RegExp(`^${parts.join('/')}$`);
  }

  match(path) {
    const match = this.regex.exec(path);
    if (!match) return null;

    return this.keys.reduce((result, key, index) => {
      result[key] = match[index + 1];
      return result;
    }, {});
  }
}

// 使用示例
const matcher = new PathMatcher('/blog/:year/:month/:slug');
const result = matcher.match('/blog/2023/10/hello-world');
// { year: '2023', month: '10', slug: 'hello-world' }

路径前缀匹配

检查路径是否以特定前缀开头:

function hasPathPrefix(path, prefix) {
  return path.startsWith(prefix) && 
    (path.length === prefix.length || path[prefix.length] === '/');
}

// 示例
hasPathPrefix('/admin/dashboard', '/admin'); // true
hasPathPrefix('/admin-dashboard', '/admin'); // false

路径规范化

处理路径中的 ... 等相对路径符号:

js 实现pathmatcher

function normalizePath(path) {
  const segments = path.split('/').filter(Boolean);
  const stack = [];

  for (const segment of segments) {
    if (segment === '.') continue;
    if (segment === '..') stack.pop();
    else stack.push(segment);
  }

  return '/' + stack.join('/');
}

// 示例
normalizePath('/a/b/.././c//d'); // "/a/c/d"

标签: jspathmatcher
分享给朋友:

相关文章

css3结合js制作

css3结合js制作

CSS3 结合 JavaScript 制作动态效果 CSS3 和 JavaScript 结合可以实现丰富的动态效果,包括动画、交互和响应式设计。以下是几种常见的实现方式: CSS3 动画与 Java…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

js怎么实现异步

js怎么实现异步

异步实现方法 JavaScript中实现异步操作主要通过以下几种方式: Promise Promise是ES6引入的异步解决方案,用于处理异步操作的成功或失败状态。 const promise =…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…