1732866795

Get parameter values from URLs with javascript


I bring up this subject because of its importance, especially for those who are building web tools. I had to learn how to deal with URL parameters here on the platform because it was very useful for building some features here on the website. You can fetch the value of a parameter from a URL with JavaScript using the `URLSearchParams` object. Here's a simple example: ```js // Example URL: https://example.com/product?id=123 const url = window.location.href; const params = new URLSearchParams(new URL(url).search); const productId = params.get('id'); console.log(productId); // "123" ``` **Explanation**: 1. `window.location.href`: Gets the full URL of the current page. 2. `new URL(url).search`: Extracts only the query string part of the URL (everything after the ?). 3. `URLSearchParams`: Allows you to manipulate the URL parameters easily. 4. `params.get('name')`: Returns the value associated with the name parameter. If the parameter does not exist, it will return null. **Using Fixed URLs**: If you want to use it with a fixed URL, do the following: ```js // Example URL: https://example.com/list?category=technology&order=asc const url = window.location.href; const params = new URLSearchParams(new URL(url).search); const category = params.get('category'); console.log(category); // "technology" const order = params.get('order'); console.log(order); // "asc" ``` This approach is compatible with most modern browsers. For very old browsers, you may need to use regex or manually split the query string.

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Terms | Donate
[2024 © Chat-to.dev]