javascript - How to get slug from an URL JavaScript
问题描述
I have the URLs for example.
- https://example.com/about?hl=en#iron
- https://example.com/product/roller/?hl=en&lo=true
- https://example.com/learn/goin/?hl=en&lo=true#iron
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)
推荐阅读
- python - 我不断收到此错误:Internal Server Error 服务器遇到内部错误,无法完成您的请求。如何解决?
- python - 如何在张量流评估期间打印当前评估步骤?
- python - 除了加载数据之外如何写尝试
- excel - Excel VBA - 插入表后更新多行上的唯一记录
- javascript - 当您通过路由更改页面时反应 CSSTransition
- flutter - 更改 Flutter 有状态小部件的最终小部件变量而状态变量不更改的原因
- c++ - 在 Qt 中包装 connect 方法隐藏了编译器所需的信息
- mongodb - MongoDB数据返回[]
- python - 将 Tensorboard 服务器添加到 Flask 端点
- ios - Swift .xib 文件表格单元格