首页 > 解决方案 > How to get slug from an URL JavaScript

问题描述

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?

标签: javascriptregexnext.js

解决方案


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)


推荐阅读