How to get all Data Values from a URL with JavaScript

Learn how to get all data values from a URL by using JavaScript’s URL constructor method.

Let’s say you’re building some type of internal search function on your website. To do that properly you need to access all the data values of a URL string.

Fortunately, JavaScript has a constructor method called new URL() that allows us to convert a URL into an object that gives us a nicely organized overview of every property and value in URLs.

To use it, create a variable, and assign it a value of new URL('your-url'). For example, below I’m creating a URL object based on a URL for one of TechStacker’s articles:

const urlData = new URL('https://techstacker.com/how-to-detect-double-clicks-with-vanilla-javascript');

Now try logging out the result:

console.log(urlData)

Your returned URL object will look similar to this:

var url = {
	hash: "",
	host: "techstacker.com",
	hostname: "techstacker.com",
	href: "https://techstacker.com/,how-to-detect-double-clicks-with-vanilla-javascript",
	origin: "https://techstacker.com",
	password: "",
	pathname: "/how-to-detect-double-clicks-with-vanilla-javascript"
	port: "",
	protocol: "https:",
	search: "",
	searchParams: "URLSearchParams {}",
	username: ""
};

And now you can easily access each property and do what you want with it. For example, to get access to the pathname of your URL, you’d do this:

console.log(url.pathname)
// Prints: "/how-to-detect-double-clicks-with-vanilla-javascript"

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on