使用regexp将含有param占位符的path转换成正则表达式

111 阅读1分钟

使用regexp将含有param占位符的path转换成正则表达式

  • 正则大法

将url中的parmas解析 /user/:name/:id,可以匹配的实例, 其中[w+]表示指所有a-z、A-Z、0-9,以及下划线

  1. 创建正则实例
    new RegExp('^' + path.router.replace(/:(\w+)/g, '\w+') + '$'))
  1. 需要匹配的对象
    new RegExp('^' + path.router.replace(/:(\w+)/g, '\w+') + '$').test(router)
  1. 完整代码
_.each(router_list, (path) => {
      //使用regexp将含有param占位符的path转换成正则表达式形式,如/user/:name/:id会转换成 ^/user/w+/w+$,
      //其中[w+]表示指所有a-z、A-Z、0-9,以及下划线。
      if (new RegExp('^' + path.router.replace(/:(\w+)/g, '\w+') + '$').test(router)) {
        ///^employee/\w+/\w+$/
        flag = true;
        return;
      }
    });