如何从 URL JavaScript 获取 slug

zum*_*mon 2 javascript regex next.js

例如,我有网址。

我想把它们变成字符串。

'about'
'product'
'learn'
Run Code Online (Sandbox Code Playgroud)

我试过了。顺便说一句,我使用Next.js。

import { useRouter } from 'next/router'

const { asPath } = useRouter()

const result = asPath.substring(1).split('?')[0].split('#')[0].split('/')[0]
Run Code Online (Sandbox Code Playgroud)

但是有没有更好的方法来处理这些问题,例如使用RegEx或其他方法?

并且也期待得到喜欢。

'about' or ['about']
'product/roller' or ['product','roller']
'learn/goin' or ['learn','goin']
Run Code Online (Sandbox Code Playgroud)

可能的?

geo*_*org 6

创建一个URL对象,获取pathname并提取非斜杠

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'))
Run Code Online (Sandbox Code Playgroud)

非正则表达式的方式是.pathname.split('/').filter(Boolean)