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

网站开发中如何从URL中获取搜索词与路径参数

路径型URL搜索词提取实现方案

你当前的URL属于路径参数形式(搜索词直接作为URL路径的一段,而非?q=xxx这类查询参数形式),可以根据你网站用的技术栈选对应实现方式:

原生JS通用方案

不依赖任何框架,所有前端环境都能用,核心逻辑是拆分URL路径段,匹配/searched/后的字段:

// 取当前页面的路径部分,忽略域名、端口、query参数
const path = window.location.pathname;
// 按斜杠拆分路径,过滤空值
const pathList = path.split('/').filter(item => item.trim() !== '');
// 定位searched字段的位置,它后面的路径段就是搜索词
const targetIndex = pathList.indexOf('searched');
let searchWord = '';
if (targetIndex !== -1 && pathList[targetIndex + 1]) {
  // 解码处理中文、特殊字符的编码情况
  searchWord = decodeURIComponent(pathList[targetIndex + 1]);
}

// 示例URL http://localhost:3000/searched/Nike 运行后,searchWord的值就是 "Nike"

如果你的搜索词可能包含斜杠(比如搜索“Nike/空军一号”这类内容),把targetIndex之后的所有路径段拼接起来即可。

常用框架快捷实现

如果你用前端框架搭建站点,路由库本身已经封装了参数读取能力,不用自己写拆分逻辑:

  • React + React Router v6
    先在路由配置里给搜索词位置加参数占位:
    <Route path="/searched/:keyword" element={<SearchResultPage />} />
    
    在搜索结果页直接调用钩子读取:
    import { useParams } from 'react-router-dom';
    function SearchResultPage() {
      const { keyword } = useParams();
      // keyword就是提取好的搜索词,框架自动完成解码
      return <div>当前搜索内容:{keyword}</div>
    }
    
  • Vue + Vue Router v4
    路由配置:
    const routes = [
      { path: '/searched/:keyword', component: SearchResultPage }
    ]
    
    页面内读取:
    <script setup>
    import { useRoute } from 'vue-router'
    const route = useRoute()
    const keyword = route.params.keyword
    </script>
    
  • Next.js
    按文件系统路由规则创建动态路由页面:App Router路径为app/searched/[keyword]/page.js,Pages Router路径为pages/searched/[keyword].js,页面内直接从props拿参数:
    // App Router示例
    export default function SearchResultPage({ params }) {
      const { keyword } = params;
      return <div>当前搜索内容:{keyword}</div>
    }
    

避坑提示:前端拼接搜索跳转链接时,记得先用encodeURIComponent对用户输入的搜索词做编码,避免中文、空格、特殊符号导致路由匹配失效、乱码问题。跳转示例:window.location.href = /searched/${encodeURIComponent(userInput)}``

内容的提问来源于stack exchange,提问作者황희윤

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 02:01:24