Beginner Fundamentals

The URL Module

The url module and the global URL class help you break a web address into parts and read its query parameters.

Parsing a URL

const myUrl = new URL("https://example.com/products?id=10&sort=price");

console.log(myUrl.hostname); // example.com
console.log(myUrl.pathname); // /products
console.log(myUrl.search);   // ?id=10&sort=price

Reading query parameters

The searchParams property gives you an easy way to read values:

const myUrl = new URL("https://example.com/products?id=10&sort=price");

console.log(myUrl.searchParams.get("id"));   // 10
console.log(myUrl.searchParams.get("sort")); // price
console.log(myUrl.searchParams.has("id"));   // true

Looping over parameters

const myUrl = new URL("https://example.com/?a=1&b=2");

for (const [key, value] of myUrl.searchParams) {
  console.log(key, "=", value);
}
// a = 1
// b = 2

Summary

The URL class turns a messy address string into structured parts. Use searchParams to read query values without manual string splitting.