请求帮助实现仅显示网页当前子目录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:
- Extract only the subdirectory part (like
/dir1/instead of the full URL) - Convert
%20back 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.pathnameis 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%23for#too).- The
ifstatement 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
相关产品推荐
相关产品推荐

