I have the URLs for example.
And I want to get these out to be string.
'about'
'product'
'learn'
I've tried. I use Next.js by the way.
import { useRouter } from 'next/router'
const { asPath } = useRouter()
const result = asPath.substring(1).split('?')[0].split('#')[0].split('/')[0]
But are there a better way to deal with these like using RegEx
or other methods?
And also looking forward to get like.
'about' or ['about']
'product/roller' or ['product','roller']
'learn/goin' or ['learn','goin']
Possible?
Create an URL
object, get the pathname
and extract non-slashes
let slug = url => new URL(url).pathname.match(/[^\/]+/g)
console.log(slug('https://example.com/about?hl=en#iron'))
console.log(slug('https://example.com/product/roller/?hl=en&lo=true'))
console.log(slug('https://example.com/learn/goin/?hl=en&lo=true#iron'))
A non-regex way would be .pathname.split('/').filter(Boolean)