In JavaScript, getting URL parameters is a very common operation, especially in web development. It is often necessary to obtain parameter values in query strings to control page display or perform API requests and other operations.
Method 1: Use the URLSearchParams object
URLSearchParams is a built-in object provided in modern browsers, which provides a convenient way to parse and get query parameters in a URL.
Code Example
Suppose we have a page URL:
?user=JohnDoe&age=30&city=NewYork
We want to get the parameter values user, age, and city in the URL.
// Get the URL of the current pageconst urlParams = new URLSearchParams(); // Get specific parameter valuesconst user = ('user'); // Get the 'user' parameterconst age = ('age'); // Get the 'age' parameterconst city = ('city'); // Get the 'city' parameter (`User: ${user}`); // Output: User: JohnDoe(`Age: ${age}`); // Output: Age: 30(`City: ${city}`); // Output: City: NewYork
explain
: Will return the query part (including the ? number) in the URL. For example, in ?user=JohnDoe&age=30&city=NewYork, "?user=JohnDoe&age=30&city=NewYork" will be returned.
: It is an interface that can easily manipulate URL query parameters. You can use its get() method to get the value of the specified parameter.
() Method: It gets a specific parameter value from the query string. If the parameter does not exist, it returns null.
Method 2: Manually parse query strings
If you need to be compatible with older versions of your browser, or for some other needs, you can manually parse query strings through native JavaScript.
Code Example
function getQueryParam(name) { const urlParams = (1); // Get the query string (remove the question mark) const params = new URLSearchParams(urlParams); return (name); } // testconst user = getQueryParam('user'); const age = getQueryParam('age'); const city = getQueryParam('city'); (`User: ${user}`); // Output: User: JohnDoe(`Age: ${age}`); // Output: Age: 30(`City: ${city}`); // Output: City: NewYork
Method 3: Use regular expressions to parse query strings
Sometimes, you may want to use regular expressions to parse URL query parameters, especially when you need to do complex parameter parsing. This approach is also suitable for older browsers.
Code Example
function getQueryParam(name) { const regex = new RegExp('[?&]' + name + '=([^&]*)', 'i'); const result = (); return result ? decodeURIComponent(result[1]) : null; } // testconst user = getQueryParam('user'); const age = getQueryParam('age'); const city = getQueryParam('city'); (`User: ${user}`); // Output: User: JohnDoe(`Age: ${age}`); // Output: Age: 30(`City: ${city}`); // Output: City: NewYork
explain
: It returns the query part in the URL (including ?). In our example, it returns "?user=JohnDoe&age=30&city=NewYork".
: The pattern of regular expression [?&]${name}=([^&]*) is used to match the value of the specified parameter in the query string.
- [?&] means that the parameter name can be before it is ? or &.
- ${name} is the parameter name you need to look for.
- ([^&]*) Match parameter values (until the end of the next & symbol or string).
: Since URL encoding may affect the readability of parameter values (such as spaces become %20), after obtaining the parameters, we use decodeURIComponent() to decode.
Method 4: Parsing the complete URL by
If you need to parse the entire URL (not just the query part), you can use different properties provided by the object (such as href, search, etc.) to extract information.
Code Example
function getQueryParamFromFullUrl(url, param) { const urlObj = new URL(url); return (param); } // Exampleconst fullUrl = "?user=JohnDoe&age=30&city=NewYork"; const user = getQueryParamFromFullUrl(fullUrl, "user"); const age = getQueryParamFromFullUrl(fullUrl, "age"); const city = getQueryParamFromFullUrl(fullUrl, "city"); (`User: ${user}`); // Output: User: JohnDoe(`Age: ${age}`); // Output: Age: 30(`City: ${city}`); // Output: City: NewYork
explain
new URL(url): Using the URL constructor, you can create a new URL object, which can easily access various parts (protocol, domain name, path, query parameters, etc.).
(): The searchParams property provides a way to access URL query parameters.
Application in actual projects
In actual projects, getting URL parameters is often used in the following scenarios:
Page redirection after form submission: You may need to pass status information in the URL, such as jumping after the form submission is successful and passing the user ID or operation status.
Paging: For example, when requesting list data, you may need to pass page parameters such as page and limit.
Filter/Search: When a user filters or searches on a page, the filter criteria is passed into the URL parameter so that the same filter state can be reloaded.
Code example: Pagination function
// Suppose we have a paging function, the URL is like: /products?page=2&limit=20 function getPaginationParams() { const urlParams = new URLSearchParams(); const page = ('page') || 1; // The default value is 1 const limit = ('limit') || 10; // The default value is 10 return { page, limit }; } const { page, limit } = getPaginationParams(); (`Current page: ${page}, Displayed per page: ${limit}`);
Summarize
Common ways to get URL parameters are:
Use URLSearchParams (recommended, suitable for modern browsers).
Use regular expressions or manual parsing (for older browsers).
Use to parse the full URL.
These methods can be flexibly selected according to your needs. In modern web development, URLSearchParams is the simplest and simplest way to use.
This is the end of this article about how to use JavaScript to obtain URL parameters. For more related contents for obtaining URL parameters in JavaScript, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!