You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何从URL中提取slug?Next.js场景下的实现方案问询

解决方案

最优实现方案(推荐:内置URL API,无依赖、兼容性强)

这种方式不需要手动处理查询参数、hash、首尾多余斜杠等边缘情况,稳定性远高于手动拆分字符串:

// Pages Router 写法
import { useRouter } from 'next/router'

const { asPath } = useRouter()
// 用临时域名补全相对路径,不影响最终提取结果
const url = new URL(asPath, 'http://placeholder.example')
// 去除路径首尾的斜杠
const cleanPath = url.pathname.replace(/^\/|\/$/g, '')

// 按需求输出对应格式
const pathSegments = cleanPath.split('/') // 数组格式:['about'] / ['product','roller']
const pathStr = cleanPath // 字符串格式:'about' / 'product/roller'
const firstSegment = pathSegments[0] // 仅取第一段的结果:'about' / 'product'

如果是Next.js 13+ App Router,可以直接用usePathname获取纯净路径,无需额外处理查询参数和hash:

// App Router 写法
import { usePathname } from 'next/navigation'

const pathname = usePathname()
const cleanPath = pathname.replace(/^\/|\/$/g, '')
// 后续格式处理和上面一致

简洁正则实现

如果希望用更短的代码实现,也可以用正则直接匹配需要的路径部分:

import { useRouter } from 'next/router'

const { asPath } = useRouter()
const match = asPath.match(/^\/([^?#]+)/)
const cleanPath = match ? match[1].replace(/\/$/, '') : ''
// 后续格式处理和上面一致

对应示例输入输出验证:

  • 输入https://example.com/about?hl=en#iron:cleanPath为about,输出'about' / ['about']
  • 输入https://example.com/product/roller/?hl=en&lo=true:cleanPath为product/roller,输出'product/roller' / ['product','roller']
  • 输入https://example.com/learn/goin/?hl=en&lo=true#iron:cleanPath为learn/goin,输出'learn/goin' / ['learn','goin']

内容的提问来源于stack exchange,提问作者zummon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 10:36:03