JavaScript如何获取URL参数及提取指定路径分段?
Hey there! Let's break down your two JavaScript URL-related questions clearly:
1. 如何使用JavaScript获取URL中的参数?
The easiest and most modern way to handle URL parameters is using the built-in URLSearchParams API—it's clean and widely supported in modern browsers.
Example for the current page's URL:
If your page's URL is something like http://localhost:8080?username=shiva&theme=dark, you can extract parameters like this:
// Grab the search parameters from the current URL const params = new URLSearchParams(window.location.search); // Get a single parameter value const username = params.get('username'); // Returns "shiva" const theme = params.get('theme'); // Returns "dark" // Loop through all parameters if you need to process them all params.forEach((value, key) => { console.log(`${key}: ${value}`); });
For a custom URL string:
If you're working with a URL that's not the current page, just wrap it in a URL object first:
const customUrl = new URL('https://example.com?product=laptop&price=999'); const params = customUrl.searchParams; console.log(params.get('product')); // Returns "laptop"
Fallback for older browsers (if needed):
If you need to support really old browsers that don't have URLSearchParams, you can manually parse the search string:
function getUrlParam(paramName) { // Remove the leading "?" from the search string const searchStr = window.location.search.substring(1); // Split into individual key-value pairs const paramPairs = searchStr.split('&'); for (const pair of paramPairs) { const [key, value] = pair.split('='); if (key === paramName) { // Decode any encoded characters (like spaces or special symbols) return decodeURIComponent(value); } } // Return null if the parameter doesn't exist return null; } // Usage const username = getUrlParam('username');
2. 提取URL中的特定路径段(比如从localhost:8080/show/myplace/中提取myplace)
You can use the URL object's pathname property to get the path part of the URL, then split it into segments and pick the one you need.
Example for the current page's URL:
const currentUrl = new URL(window.location.href); // Get the path (e.g., "/show/myplace/" for your example) const path = currentUrl.pathname; // Split the path by "/" and filter out empty strings (from leading/trailing slashes) const pathSegments = path.split('/').filter(segment => segment); // In your example, pathSegments will be ["show", "myplace"] // Pick the second segment (index 1, since arrays are 0-indexed) const targetSegment = pathSegments[1]; // Returns "myplace"
For a custom URL string:
Note that the URL constructor requires a full URL including the protocol (like http://), so if your input doesn't have it, just prepend it:
const urlStr = 'localhost:8080/show/myplace/'; const url = new URL(`http://${urlStr}`); const pathSegments = url.pathname.split('/').filter(seg => seg); const targetSegment = pathSegments[1]; // Returns "myplace"
A quick note: The filter(segment => segment) step is important because splitting a path like /show/myplace/ with / will give you ["", "show", "myplace", ""]—we want to get rid of those empty strings to work with only valid path segments.
内容的提问来源于stack exchange,提问作者shiva

