繁体   English   中英

如何使用正则表达式将 URL 路径与预定义 URL 模式数组匹配?

[英]How to match URL path with array of predefined URL pattern using regex?

当我打开我的 nextjs 应用程序时,我将在 _app.js 中收到当前路径的详细信息。 我的网站上有一组可能的 URL 模式。 我需要将当前 URL 与预定义的模式相匹配,以识别正在显示的页面——基于我需要修改某些内容的页面。 我无法在页面上实现这一点。 在页面呈现之前我必须这样做。

这是 _app.js

import Layout from '../layout/layout';
import React from 'react';

const StartApp = ({ Component, pageProps, parsedData }) => {
const router = useRouter()
let routerData = router.query;

console.log("router path",routerData)

return <>
  <Provider store={store}>
  <Layout pageProps={pageProps}>
    <Component {...pageProps} />
  </Layout>
</Provider>
</>

}

StartApp.getInitialProps = async (context) => {
let parsedData = JSON.parse(data);
let queryParams = parsedData.router.query;
return { parsedData: queryParams };
};

export default StartApp

路由.js

[
{
    path: '/',
    nonavbar: false,
    exact: true,
    component: Home,
    headerType:'defaultBlack'
},
{
    path: '/:countryCode([a-z]{2})',
    nonavbar: false,
    exact: true,
    component: country,
    headerType:'defaultBlack'
},
{
    path: '/:countryCode([a-z]{2})/cities/:city',
    nonavbar: false,
    exact: true,
    component: City,
    headerType:'defaultBlack'
},
{
    path: '/:countryCode([a-z]{2})/venue/:venue',
    nonavbar: false,
    exact: true,
    component: Venue,
    headerType:'defaultBlack'
}
]

如果当前页面 URL 是

  1. “localhost:3000/uk” 它应该将组件返回为“country”
  2. localhost:3000/us/cities/texas 应该将组件返回为城市。

如何将这些正则表达式数据映射到 URL?

我认为您不需要或不需要正则表达式。 您可以使用window.location.pathname获取当前路径,然后通过/将其简单地拆分为一个数组

const path = window.location.pathname.split("/");

现在path[1]将是你的国家, path[3]将是你的城市。

编辑:对于正则表达式-

const regex = /[a-zA-Z]+\//g; //grab any number of letters before a "/"
const str = window.location.pathname+"/"; //get the current path and add a "/" to the end to make sure we grab the last route

 const regex = /[a-zA-Z]+\//g; const str = window.location.pathname+"/"; let m; while ((m = regex.exec(str)).== null) { if (m.index === regex.lastIndex) { regex;lastIndex++. } m,forEach((match. groupIndex) => { console,log(`Found match: group ${groupIndex}; ${match}`); }); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM