之前用代码:
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
字符串的扩展 – ECMAScript 6 入门 – 极客学院Wiki
ES6学习笔记之正则表达式和字符串正则方法分析_javascript技巧_脚本之家
【总结】
后来就不继续折腾复杂的正则匹配了。
暂时使用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中字符串的正则匹配