How to Parse a URL in JavaScript?

Parsing a URL in JavaScript is simple with the built-in URL object. Here's how to do it:

  1. Creating a URL Object
let url = new URL("https://example.com/path?name=value#hash");
  1. Accessing URL Properties
console.log(url.protocol); // Output: https:
console.log(url.hostname); // Output: example.com
console.log(url.pathname); // Output: /path
console.log(url.search); // Output: ?name=value
console.log(url.hash); // Output: #hash
  1. Working with URL Parameters
// Get a specific URL parameter
let name = url.searchParams.get("name"); // Output: value

// Set a new URL parameter
url.searchParams.set("newParam", "newValue");

// Check if a URL parameter exists
let hasParam = url.searchParams.has("name"); // Output: true

// Delete a URL parameter
url.searchParams.delete("name");
  1. Iterating Over URL Parameters
for (let pair of url.searchParams.entries()) {
  console.log(pair[0] + ", " + pair[1]);
}

With the URL object, parsing a URL in JavaScript is straightforward.

Lastly, if you want to grab query parameters from any url without using javascript, use parseurlonline.com to quickly get the data without any hassle.