0

When I open my nextjs application, I will receive the current path details in _app.js. And I have a collection of possible URL patterns on my site. I need to match the current URL to the predefined patterns to identify which page is displaying—based on the page I need to modify some content. I can't implement this on pages. before the page render I have to do this.

This is _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

Routes.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'
}
]

If the current page URL is

  1. "localhost:3000/uk" It should return the component as "country"
  2. localhost:3000/us/cities/texas should return the component as city.

How can I map these regex data with URL?

Ajith Arasu
  • 79
  • 10

1 Answers1

0

I don't think you want or need regex for this. You can grab the current path with window.location.pathname and then simply split it into an array by /

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

now path[1] would be your country, path[3] would be your city.

Edit: For regex-

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}`);
    });
}
Brandon
  • 389
  • 1
  • 8
  • Thanks for your answer. But there is a chance for getting city and venue both components. they both are the same length. I have many patterns like this. – Ajith Arasu Dec 23 '22 at 07:56
  • @AjithArasu and wouldn't `path[2]` tell you if it's a city or venue? I'll edit my answer with the regex. – Brandon Dec 23 '22 at 07:59