in pure js how to get query paramters from url?
- User
in pure js how to get query paramters from url?
- Assistant
in pure js how to get query paramters from url?
In pure JavaScript, you can retrieve query parameters from a URL using several methods. The most modern and straightforward way is by utilizing the URL and URLSearchParams interfaces. Below are different approaches to achieve this:
URL and URLSearchParams (Modern Approach)This is the recommended method as it provides a clean and easy-to-use API for handling URLs and their components.
// Suppose the current URL is: https://example.com/page?name=JohnDoe&age=25
// Create a new URL object from the current window's URL
const url = new URL(window.location.href);
// Access the search parameters using URLSearchParams
const params = new URLSearchParams(url.search);
// Get specific query parameters
const name = params.get('name'); // "JohnDoe"
const age = params.get('age'); // "25"
console.log(name); // Output: JohnDoe
console.log(age); // Output: 25
Explanation:
window.location.href provides the full URL of the current page.new URL(window.location.href) creates a URL object.url.search retrieves the query string (e.g., ?name=JohnDoe&age=25).new URLSearchParams(url.search) creates an object to work with the query parameters..get('paramName') retrieves the value of a specific parameter.window.location.search DirectlyIf you prefer not to use the URL object, you can directly work with window.location.search.
// Example URL: https://example.com/page?name=JohnDoe&age=25
// Get the query string from the URL
const queryString = window.location.search; // "?name=JohnDoe&age=25"
// Create a URLSearchParams object
const params = new URLSearchParams(queryString);
// Retrieve parameters
const name = params.get('name'); // "JohnDoe"
const age = params.get('age'); // "25"
console.log(name); // Output: JohnDoe
console.log(age); // Output: 25
Sometimes it's convenient to have all query parameters in a JavaScript object. Here's how you can do it:
// Example URL: https://example.com/page?name=JohnDoe&age=25&city=NewYork
// Function to convert query parameters to an object
function getQueryParams() {
const params = new URLSearchParams(window.location.search);
const paramsObj = {};
for (const [key, value] of params.entries()) {
// If the key already exists, convert it to an array
if (paramsObj.hasOwnProperty(key)) {
if (Array.isArray(paramsObj[key])) {
paramsObj[key].push(value);
} else {
paramsObj[key] = [paramsObj[key], value];
}
} else {
paramsObj[key] = value;
}
}
return paramsObj;
}
// Usage
const queryParams = getQueryParams();
console.log(queryParams);
// Output: { name: "JohnDoe", age: "25", city: "NewYork" }
Explanation:
getQueryParams function iterates over all entries in the query string.If a query parameter can have multiple values (e.g., ?tag=javascript&tag=web), you can retrieve all values using the getAll method:
// Example URL: https://example.com/page?tag=javascript&tag=web&tag=development
const params = new URLSearchParams(window.location.search);
// Get all values for the 'tag' parameter
const tags = params.getAll('tag'); // ["javascript", "web", "development"]
console.log(tags); // Output: ["javascript", "web", "development"]
Before URLSearchParams, developers often manually parsed the query string. While this method works, it's more error-prone and less efficient.
// Example URL: https://example.com/page?name=JohnDoe&age=25
function getQueryParamsManual() {
const queryString = window.location.search.substring(1); // Remove the "?"
const params = queryString.split('&');
const paramsObj = {};
params.forEach(param => {
const [key, value] = param.split('=');
// Decode URI components to handle encoded characters
const decodedKey = decodeURIComponent(key);
const decodedValue = decodeURIComponent(value || '');
// Handle multiple parameters with the same name
if (paramsObj.hasOwnProperty(decodedKey)) {
if (Array.isArray(paramsObj[decodedKey])) {
paramsObj[decodedKey].push(decodedValue);
} else {
paramsObj[decodedKey] = [paramsObj[decodedKey], decodedValue];
}
} else {
paramsObj[decodedKey] = decodedValue;
}
});
return paramsObj;
}
// Usage
const queryParams = getQueryParamsManual();
console.log(queryParams);
// Output: { name: "JohnDoe", age: "25" }
Note: While manual parsing provides more control, it's generally better to use URLSearchParams for reliability and simplicity.
Regular expressions can also be used to parse query parameters, but they can become complex and are not recommended for this purpose.
// Example URL: https://example.com/page?name=JohnDoe&age=25
function getQueryParamByRegex(param) {
const regex = new RegExp('[?&]' + param + '(=([^&#]*)|&|#|$)');
const results = regex.exec(window.location.href);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
// Usage
const name = getQueryParamByRegex('name'); // "JohnDoe"
const age = getQueryParamByRegex('age'); // "25"
console.log(name); // Output: JohnDoe
console.log(age); // Output: 25
Caution: This method can be less reliable and harder to maintain compared to using URLSearchParams.
For modern web development, using URL and URLSearchParams is the most efficient and clean way to handle query parameters in pure JavaScript. It abstracts away the complexities of parsing and provides useful methods to interact with the query string.
Example: Complete Usage with URLSearchParams
// Get the current URL
const currentUrl = window.location.href;
// Create a URL object
const url = new URL(currentUrl);
// Access query parameters
const params = new URLSearchParams(url.search);
// Iterate over all parameters
params.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
// Access specific parameter
const specificParam = params.get('paramName');
console.log(specificParam);
This approach ensures your code is readable, maintainable, and leverages built-in browser APIs for optimal performance.
Not yet included in a published release.