Estoy usando next.js y tengo la siguiente estructura de página, el valor se almacena en path
www.mysite.com/countries www.mysite.com/countries/africa www.mysite.com/countries/asia www.mysite.com/countries/europe Tengo subpáginas debajo de cada página: el valor se almacena en slug :
www.mysite.com/countries/africa/sudan www.mysite.com/countries/africa/kenya ...Quiero comprobar si la babosa está en el camino:
slug.includes(path) si el slug es www.mysite.com/countries/africa esto también se vuelve verdadero para www.mysite.com/countries que no quiero.
Solo quiero www.mysite.com/countries/africa y www.mysite.com/countries/africa/[any countries] , probé diferentes formas pero no puedo obtener esta condición correctamente.
Yo uso regex const regex = /countries\/(.*)\/(.*)|countries\/(.*)/; para filtrar path = window.location.pathname . Por ejemplo, configuraré la ruta manualmente.
Puede consultar la siguiente demostración:
// 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'); }