I am using next.js and I have the following page structure, the value is stored in path
www.mysite.com/countries
www.mysite.com/countries/africa
www.mysite.com/countries/asia
www.mysite.com/countries/europe
I have sub pages under each page - value is stored in slug:
www.mysite.com/countries/africa/sudan
www.mysite.com/countries/africa/kenya
...
I want to check if slug is in the path:
slug.includes(path)
if the slug is www.mysite.com/countries/africa this also returns true for www.mysite.com/countries which I dont want.
I just want www.mysite.com/countries/africa and www.mysite.com/countries/africa/[any countries], I tried different ways but cant get this condition right.
I use regex const regex = /countries\/(.*)\/(.*)|countries\/(.*)/; to filter path = window.location.pathname. For example, I will set path manually.
You can check the below demo:
// Runing on real environment
// var path = window.location.pathname;
// Path start with /
// Uncomment to try the below example
// var path = '/countries/africa/sudan';
var path = '/countries/africa';
const regex = /countries\/(.*)\/(.*)|countries\/(.*)/;
var result = path.match(regex);
if (result) {
const land = result[1] !== undefined ? result[1] : result[3];
const country = result[2];
if (land == 'africa') {
if (country !== undefined) {
// this match for www.mysite.com/countries/africa/[any countries]
console.log('matched to country of africa URL');
} else {
// this match for www.mysite.com/countries/africa
console.log('matched to africa URL');
}
} else {
console.log('not matched to africa URL');
}
} else {
console.log('not matched');
}