Ever found yourself needing to extract specific data from a URL in JavaScript? W3Schools offers a straightforward method to achieve this – using the URLSearchParams interface. Let's delve into how you can effectively use this to retrieve URL parameters.

To demonstrate, consider a URL like this: example.com/?name=John&age=30. Here, 'name' and 'age' are parameters, with values 'John' and '30' respectively. We'll show you how to extract these values using JavaScript.

Understanding URL Parameters
URL parameters are key-value pairs appended to the end of a URL. They start with a question mark '?', followed by the key-value pairs separated by '&'. For instance, in example.com/?color=blue&size=M, 'color' and 'size' are the parameters.

Now that we understand URL parameters, let's move on to extracting them using JavaScript.
Creating a URLSearchParams Object

The URLSearchParams interface allows you to work with the URL parameters. To create a URLSearchParams object, you can use the 'new URLSearchParams' constructor. Here's how you might do it:
let params = new URLSearchParams(window.location.search);
In this example, window.location.search returns the URL query string ( everything after the '?').

Accessing the URL Parameters
After creating the URLSearchParams object, you can access the parameters using methods like get() and has(). Here's how you can extract the 'name' and 'age' parameters from our earlier example:
- let name = params.get('name'); returns 'John'.
- params.has('age'); returns true because 'age' is a parameter.

You can also loop through all the parameters using the for...of loop:
for(let pair of params) console.log(pair[0]+ ', ' + pair[1]); will log 'name, John', 'age, 30'



















Working with Multiple Pages
So far, we've focused on extracting parameters from the current page. But what if you want to extract parameters from other pages? Let's say you have a URL like example.com/page? ordres=12345 and you want to extract the 'orders' parameter even though you're not on the 'page' page. To do this, you can define a function:
Extracting Parameters from Other Pages
Here's a function that takes a URL and a parameter name, then returns the value of that parameter:
function getParam(url, param) { let params = new URLSearchParams(new URL(url).search); return params.get(param); }
You can use this function like this: getParam('https://example.com/page?orders=12345', 'orders') which will return '12345'.
Mastering how to extract URL parameters in JavaScript is a crucial aspect of web development. With the knowledge you've gained here, you're well on your way to enhancing your web applications' interactivity. Happy coding!