When working with web applications, you often need to extract query parameters from a URL. Query parameters are typically used to send data to web applications like search requests, pagination data, etc. The modern way to handle URLs and query parameters in JavaScript is by using the URL and URLSearchParams objects. Let's delve into how you can effectively extract query parameters via JavaScript.

Understanding URLs and Query Parameters

A typical URL with query parameters looks like this: https://example.com?name=John&age=30. The part after the question mark (?) is called the query string. This query string contains key-value pairs, each separated by an ampersand (&).

The URL Object

The URL object is part of the modern JavaScript specification that provides an easy way to parse URLs, get or set various components such as the hostname, pathname, and of course, query parameters. Below is a simple way to instantiate a URL object:

const url = new URL('https://example.com?name=John&age=30');

Once you have the URL object, you can access different properties like url.hostname, url.pathname, and others with ease.

Using URLSearchParams to Extract Query Parameters

The URLSearchParams object can be instantiated from the search string of the URL object. Let’s see it in action:

const searchParams = new URLSearchParams(url.search);

With the searchParams object, you can perform a variety of operations such as getting all parameter names and values, checking if a certain key exists, and more. Here are some examples:

Getting a Single Parameter Value

const name = searchParams.get('name'); // 'John'
const age = searchParams.get('age');   // '30'

Checking if a Parameter Exists

const hasAge = searchParams.has('age'); // true

Retrieving All Parameters

If you want to loop through all the query parameters, you can use the for...of construct:

for (const [key, value] of searchParams) {
  console.log(`${key}: ${value}`);
}
// Output:
// name: John
// age: 30

Handling Multiple Values

Query parameters can also have multiple values: https://example.com?name=John&interest=music&interest=art. You can get all values for a parameter using the getAll method:

const interests = searchParams.getAll('interest');
console.log(interests); // ['music', 'art']

Modifying Query Parameters

URLSearchParams also allows you to modify the query parameters easily, which is especially useful for generating dynamic URLs or updating the URL in a Single Page Application (SPA).

Adding a New Parameter

searchParams.append('city', 'NewYork');
console.log(url.href); // 'https://example.com?name=John&age=30&city=NewYork'

Setting (Updating) a Parameter

searchParams.set('age', '31');
console.log(url.href); // 'https://example.com?name=John&age=31&city=NewYork'

Deleting a Parameter

searchParams.delete('city');
console.log(url.href); // 'https://example.com?name=John&age=31'

Conclusion

Using the URL and URLSearchParams objects, JavaScript provides robust methods for working with query parameters. This is a more modern, flexible, and cleaner approach compared to older methods like regular expressions or manual string manipulation. With these tools, handling URLs and extracting query parameters becomes efficient and straightforward, whether you're fetching values, updating them, or constructing new query strings for additional utility in your web applications.