正则表达式获取路径中所有的变量

154 阅读1分钟
  • while跟正则方法exec搭配使用可以将捕获的分组全部获取到
  • 比如: a/{projectPath}/{itemPath}/{path},这三个path都可以在while中res输出

 // 解析是否存在参数,存在参数并且解析出来
 const path = a/{projectPath}/{itemPath}/{path}
    const reg = /{(.*?)}/g;
    let res = null;
    const pathFormListArr = [];
    let i = 0;
    while ((res = reg.exec(path))) {
      console.log('res', res);
      if (pathFormList[i]) {
        pathFormListArr.push({
          parameterExample: pathFormList[i].parameterExample,
          note: pathFormList[i].note,
          key: new Date().getTime() + res[1] + Math.random(),
          name: res[1],
        });
      } else {
        pathFormListArr.push({
          key: new Date().getTime() + res[1] + Math.random(),
          name: res[1],
          parameterExample: '',
          note: '',
        });
        i++;
      }
    }