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

React路由中如何将斜杠/作为纯文本使用而非路径分隔符?

解决路由中斜杠作为文本的问题

当你需要把带斜杠的字符串(比如"apples/oranges?")用作路由时,核心是不让斜杠被路由解析器当成路径分隔符,下面是几种实用方案:

  • URL编码/解码
    把斜杠、问号这类特殊字符转换成URL安全的编码,路由用编码后的字符串,获取时再解码还原。
    示例代码(JavaScript):

    // 编码
    const originalId = "apples/oranges?";
    const encodedId = encodeURIComponent(originalId);
    // 此时encodedId为 "apples%2Foranges%3F",可直接用作路由,比如 /items/apples%2Foranges%3F
    
    // 解码(目标页面获取ID时)
    const decodedId = decodeURIComponent(encodedId);
    // decodedId会还原为 "apples/oranges?"
    
  • 替换特殊字符
    把斜杠换成路由不会识别的自定义字符,后续再替换回来。比如用__slash__代替/,用__q__代替?:

    // 替换
    const safeId = "apples/oranges?".replace(/\//g, "__slash__").replace(/\?/g, "__q__");
    // safeId为 "apples__slash__oranges__q__",用作路由 /items/apples__slash__oranges__q__
    
    // 还原
    const originalId = safeId.replace(/__slash__/g, "/").replace(/__q__/g, "?");
    

    注意替换的字符要选不会出现在正常ID里的,避免冲突。

  • 用查询参数传递ID
    别把ID放在路由路径里,而是作为查询参数传递。比如路由设为/items?id=apples/oranges?,在目标页面通过查询参数获取:

    // 目标页面获取ID
    const params = new URLSearchParams(window.location.search);
    const id = params.get("id");
    // id就是 "apples/oranges?"
    

    这种方式最直接,不用处理编码或替换,适合不需要把ID作为路径一部分的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:10:29