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

请求帮助实现仅显示网页当前子目录URL并解决空格编码问题

Hey there! Let's work through this together—since you're new to coding, I'll keep this simple and break down every step.

What we need to fix:

  1. Extract only the subdirectory part (like /dir1/ instead of the full URL)
  2. Convert %20 back to regular spaces so they display correctly

Solution 1: Get the full subdirectory path (with spaces fixed)

Replace your existing script with this code:

<p3>
  <script>
    // Grab the part of the URL after the domain (e.g., "/dir1" from "example.com/dir1")
    let path = location.pathname;
    // Decode URL-encoded characters (turns "%20" into a regular space)
    let decodedPath = decodeURI(path);
    // Add a trailing slash if it's not already there (and we're not at the root)
    if (decodedPath !== '/' && !decodedPath.endsWith('/')) {
      decodedPath += '/';
    }
    // Write the final result to the page
    document.write(decodedPath);
  </script>
</p3>

How this works:

  • location.pathname is a built-in browser property that directly gives you the path after the domain—no need to mess with the full URL.
  • decodeURI() handles all URL-encoded characters (not just %20, it works for things like %23 for # too).
  • The if statement makes sure we always have a trailing slash, matching your example of /dir1/.

Solution 2: Get only the first-level subdirectory (if that's what you need)

If you want to show just the top-level subdirectory (e.g., /dir1/ even if the URL is example.com/dir1/subdir), use this instead:

<p3>
  <script>
    let path = location.pathname;
    let decodedPath = decodeURI(path);
    // Split the path into parts and remove empty strings
    let pathSegments = decodedPath.split('/').filter(segment => segment !== '');
    // If there's a subdirectory, format it with slashes; otherwise show root
    let firstSubdir = pathSegments.length > 0 ? `/${pathSegments[0]}/` : '/';
    document.write(firstSubdir);
  </script>
</p3>

Just copy whichever code fits your needs into your <p3> tag, and it should work exactly how you want!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:46:21