最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】ES6中字符串的正则匹配

JS crifan 3818浏览 0评论

之前用代码:

    if (pageType === ROUTER_PAGE.NONE){
      for (let eachPageKey of Object.keys(ROUTER_PAGE)){
        console.log("——–");
        const eachPage = ROUTER_PAGE[eachPageKey];
        const toCompareUrl = `${ENV_PREFIX}${eachPage.urlPattern}`;
        console.log(`currentUrl=${currentUrl},toCompareUrl=${toCompareUrl}`);
        const matched = currentUrl.match(toCompareUrl);
        console.log(`matched=${matched}`);
        if (matched !== null) {
          console.log(`Found match matched=${matched}`);
          pageType = eachPage;
          break;
        }
      }
    }

结果:

currentUrl=/breedingAdd/0,toCompareUrl=/
index.js?5c2a:335 matched=/
index.js?5c2a:338 Found match matched=/

即:

对于:

当前url来说:

/breedingAdd/0

去匹配

/

结果竟然是可以匹配到的:

/

不是以为:

匹配不到,返回null

所以要去找js中的字符串的正则匹配

ES6 字符串 正则匹配

每天学点ES6-字符串 | Cookfront’s Blog

ES6中新的正则表达式规则 | Lucas

字符串的扩展 – ECMAScript 6 入门 – 极客学院Wiki

ES6学习笔记之正则表达式和字符串正则方法分析_javascript技巧_脚本之家

后 ES6 时代的正则匹配 – 众成翻译

【总结】

后来就不继续折腾复杂的正则匹配了。

暂时使用startsWith吧:

    // 2. if above not same url, then try match prefix
    // and exclue the NONE and MAIN(its url pattern is /)
    if (pageType === ROUTER_PAGE.NONE){
      for (let eachPageKey of Object.keys(ROUTER_PAGE)){
        console.log("——–");
        const eachPage = ROUTER_PAGE[eachPageKey];
        if ((eachPage === ROUTER_PAGE.NONE) || (eachPage === ROUTER_PAGE.MAIN)) {
          continue;
        }
        const toCompareUrl = `${ENV_PREFIX}${eachPage.urlPattern}`;
        //const matched = currentUrl.match(toComparePattern);
        const matched = currentUrl.startsWith(toCompareUrl);
        console.log(`toCompareUrl=${toCompareUrl}, currentUrl=${currentUrl} -> matched=${matched}`);
        // const toComparePattern = `/^${toCompareUrl}/ig`;
        // console.log(`toComparePattern=${toComparePattern}`);
        // const isMatch = toComparePattern.test(currentUrl);
        // console.log(`toCompareUrl=${toCompareUrl},toComparePattern=${toComparePattern}, currentUrl=${currentUrl} -> isMatch=${isMatch}`);
        // if (isMatch) {
        // if (matched !== null) {
        if (matched) {
          pageType = eachPage;
          break;
        }
      }
    }

然后去匹配:

toCompareUrl=/breedingProcess, currentUrl=/breedingAdd/0 -> matched=false
index.js?5c2a:333 ——–
index.js?5c2a:344 toCompareUrl=/breedingAdd, currentUrl=/breedingAdd/0 -> matched=true
index.js?5c2a:362 parsePageType: currentUrl=/breedingAdd/0 -> page=新增配种

转载请注明:在路上 » 【已解决】ES6中字符串的正则匹配

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.185 seconds, using 22.05MB memory