Skip to main content Accessibility Feedback

Getting values from a URL with vanilla JS

Let’s say you have a URL string, like this.

var str = '';

If you need to get the hash (#using-the-fetch-api) or the URL search parameters (?query=fetch&page=2) from the string, how would you?

Today, we’re going to learn how to get data from a URL string using the URL() constructor method.

Creating a URL object

We can convert the URL string into a URL object using the new URL() constructor.

var url = new URL('');

If you had a relative URL with a different base URL then the current site, you could also pass that base in as an optional second argument.

var relativeURL = new URL('/search?query=fetch&page=2#using-the-fetch-api', '');

This returns a new URL object that looks like this.

var url = {
	hash: "#using-the-fetch-api",
	host: "",
	hostname: "",
	href: "",
	origin: "",
	password: "",
	pathname: "/search",
	port: "",
	protocol: "https:",
	search: "?query=fetch&page=2",
	searchParams: "URLSearchParams {}",
	username: ""

Now, you can easily snag properties from the URL string.

Here’s a demo.

Working with search parameter values

The URL() object also provides some handy methods for working with search parameters in your URL.

One of the properties on the returned object is search. You can use that to get the entire search parameter string.

// logs "?query=fetch&page=2"

But what if you wanted to get the value of query or page?

For that, we have the URLSearchParams() object, which is automatically mapped to the searchParams property in the object returned from the URL() constructor.

It contains a handful of methods for getting, setting, and deleting search parameters.

// Get the value for the the "query" parameter
// returns "fetch"

// Gets all matching values, if there's more than one
// returns ["fetch"]

// Checks if a value exists in the search params (boolean)
// returns true

// Gets an Iterator of keys
// Iterators can be looped through with a for...of

// Gets an iterator of values

// Appends a new search parameter entry
// This adds an *additional* entry if the key already exists
url.searchParams.append('query', 'chicken');

// Sets a search parameter entry
// If the value already exists, it will replace it
// If there are more than one, all others are deleted
url.searchParams.set('query', 'chicken');

// Deletes all instances of a search parameter

// Provides an iterator method for looping through search parameter values
url.searchParams.forEach(function (value, key) {
	console.log(key, value);

// Sorts search parameters alphabetically by key

Browser Compatibility

The URL() and URLSearchParams() constructors work in all modern browsers, but not IE. They can be polyfilled with