How To Get URL Parts In Javascript – Host, Path, File, Query, ETC…

Welcome to a quick tutorial on how to get the full URL and parts in Javascript. Need to extract certain parts of the URL? Here are some of the common ones:

  • Use window.location.href to get the full URL. For example – http://site.com/foo/bar.html?key=value
  • Use window.location.origin to get the protocol and hostname. For example – http://site.com/
  • Use window.location.origin + window.location.pathname to get the hostname and path. For example – http://site.com/foo/

Yep, and there are a lot more on getting the specific URL parts in Javascript. So let us walk through some examples in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes URL & Parts Derived Parts
Query String Useful Bits & Links The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

GETTING THE FULL URL & PARTS

In this first section, we will be walking through the parts of a URL, and how we can get them in Javascript.

 

DEBUNKING THE URL MYSTERY PARTS

Before we go into the scripts, let us quickly break down the different parts of a URL:

Heh, and I thought the URL is supposed to be easily understood by humans? It really is not so “human” now aye?

 

HOW TO GET THE URL PARTS IN JAVASCRIPT

So now that you know the parts of a URL, here is how we get the individual parts – Javascript is thankfully very convenient, and window.location pretty much contains all the various URL parts that we can use:

Variable Description
window.location.href This will give you the full URL.

http://site.com:8080/folder/test.html?p=123

window.location.protocol Contains the protocol.

http://site.com:8080/folder/test.html?p=123

window.location.hostname Contains the hostname.

http://site.com:8080/folder/test.html?p=123

window.location.host Contains the hostname and the port, this one is kind of confusing. Since we normally don’t define the port for HTTP and HTTPS, this will be the same as hostname most of the time.

http://site.com:8080/folder/test.html?p=123

window.location.origin Contains the protocol, hostname, and port.

http://site.com:8080/folder/test.html?p=123

window.location.port Contains the port number.

http://site.com:8080/folder/test.html?p=123

window.location.pathname Contains the path and file name.

http://site.com:8080/folder/test.html?p=123

window.location.search Contains the query string or parameter.

http://site.com:8080/folder/test.html?p=123

window.location.hash Contains the hash anchor.

http://site.com:8080/folder/test.html#section-abc

 

 

DERIVED URL PARTS

As convenient as Javascript may be, there are still a few “URL parts” that we have to derive by ourselves.

 

GET THE FILE NAME ONLY

http://site.com:8080/folder/test.html?p=123

So yeah, the file name is missing from window.location, and here is how we derive it with a few extra lines of script:

file-name-only.js
// Get the current path first
var dafile = window.location.pathname;

// You can extract the current path, then strip out all the folders
dafile = dafile.substring(dafile.lastIndexOf('/')+1);

// Or use regular expression to strip the folders out
dafile = dafile.replace(/^.*[\\\/]/, '');

console.log(dafile);

 

GET THE FOLDER ONLY

http://site.com:8080/folder/test.html?p=123

Now, if you want the folder only, here is how with a few lines of code:

folder-only.js
var folder = window.location.pathname;
folder = folder.substr(0, folder.lastIndexOf('/'));
console.log(folder);

 

 

GET THE BASE URL

http://site.com:8080/folder/test.html?p=123

Combining the various parts together, you can reform the base URL:

base-url.js
var folder = window.location.pathname;
folder = folder.substr(0, folder.lastIndexOf('/'));
var baseUrl = window.location.protocol + "//" + window.location.host + "/" + folder ;
console.log(baseUrl);

 

PARSE A GIVEN URL

So what if we want to parse a given URL? We simply do a “hack” and create a dummy anchor element:

parse-url.js
// Create a dummy anchor
var parser = document.createElement('a');

// Specify an URL
parser.href = "https://codeboxx.com/folder/inside/test.html?foo=bar";

// Magic. All the location properties now work "as usual".
console.log(parser.hostname);
console.log(parser.pathname);
console.log(parser.search);

 

 

QUERY STRING

As in the first section above, you can get the query string with window.location.search, but this is a little bit of an extra on working with the query string – I have seen a number of guides on the Internet still using the “old parse string into array” way of working with query strings. Here is an example of an easier way with the URLSearchParams API.

 

PARAMETERS MAGIC

query-yoga.js
// Let's go with the old example of ?p=123&hello=world
var daquery = new URLSearchParams(window.location.search);

// has & get
console.log(daquery.has('hello')); // true
console.log(daquery.get('hello')); // world

// Looping through the keys
for (var key of daquery.keys()) { console.log(key); } // p, hello

// append, set, delete
daquery.append("plurk", "dis"); // The query string will now be p=123&hello=world&plurk=dis
daquery.set("hello", "kitty"); // This will replace hello=world to hello=kitty
daquery.delete("p"); // Removes p=123, the query string will now be hello=kitty&plurk=dis

// to string
var daquerystring = daquery.toString(); // This will simply output the query as a string
Function Description
has (key) Checks if the query string contains the given key.
get (key) Get the value of the given key.
append (key, value) Append a new key/value pair to the query string
set (key, value) Sets the query string with the given key/value pair, will override the existing.
delete (key) Delete the given key/value from the query string.
toString () Converts the query into a flat string.

Of course, these are only a few commonly used ones, and you can read more of it at Mozilla developer.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEATSHEET

Cheat sheet – Getting URL Parts with Javascript (Click to enlarge)

 

REFERENCES & LINKS

 

THE END

Thank you for reading, and we have come to the end of this short guide. I hope it has explained the URL mystery to you, and if there are body URL parts that I have missed out, please feel free to let me know in the comments below. Good luck and happy coding!

1 thought on “How To Get URL Parts In Javascript – Host, Path, File, Query, ETC…”

Leave a Comment

Your email address will not be published. Required fields are marked *