Get URL Parts In Javascript (Host, Path, File, Query, ETC…)

Welcome to a 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 location.href to get the full URL. For example – http://site.com/path/file.html?key=value
  • Use location.origin to get the protocol and hostname. For example – http://site.com/
  • Use location.pathname to get the path and file name. For example – /path/file.html

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

 

 

TABLE OF CONTENTS

 

GETTING THE FULL URL & PARTS

All right, let us now get into the examples and ways to get the URL and parts in Javascript.

 

PARTS OF THE URL

Before we proceed, here is a quick recap of the parts of the URL:

Yep, URLs are supposed to be “humanly legible”, but it is not really that straightforward.

 

 

PART 1) WINDOW LOCATION

When it comes to the URL, Javascript thankfully has a convenient window.location object (or just location for short). It pretty much contains all the various URL parts that we can use “out of the box”:

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

http://site.com:8080/path/file.html?p=123

location.protocol Contains the protocol.

http://site.com:8080/path/file.html?p=123

location.hostname Contains the hostname.

http://site.com:8080/path/file.html?p=123

location.host Contains the hostname and the port.

http://site.com:8080/path/file.html?p=123

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

http://site.com:8080/path/file.html?p=123

location.port Contains the port number.

http://site.com:8080/path/file.html?p=123

location.pathname Contains the path and file name.

http://site.com:8080/path/file.html?p=123

location.search Contains the query string or parameter.

http://site.com:8080/path/file.html?p=123

location.hash Contains the hash anchor.

http://site.com:8080/path/file.html#section-abc

 

 

PART 2) DERIVED URL PARTS

If the “URL part” that you require is not in location, the only way is to derive it yourself. Here are some of the common ones.

 

2A) FILE NAME ONLY

http://site.com:8080/path/file.html?p=123

2-derived.html
// (A) FILE NAME ONLY
var fileonly = location.pathname;
// fileonly = fileonly.substring(fileonly.lastIndexOf("/")+1);
fileonly = fileonly.replace(/^.*[\\\/]/, "");
console.log(fileonly);
  • location.pathname will give us the path and file name.
  • We can use substring to “remove” the /path/ part.
  • Or use replace regular expression to “extract” the file name only.

 

2B) PATH ONLY

http://site.com:8080/path/file.html?p=123

2-derived.html
var pathonly = location.pathname;
pathonly = pathonly.substr(0, pathonly.lastIndexOf("/"));
console.log(pathonly);

This is similar to the “filename only”. But we strip out the file name and keep the path section instead.

 

 

2C) BASE URL

http://site.com:8080/path/file.html?p=123

2-derived.html
// (C) BASE URL
var baseurl = `${location.protocol}//${location.host}${pathonly}/`;
console.log(baseurl);

This one should be straightforward. We “combine” the protocol, host, and derived path earlier to get the current base URL.

 

PART 3) WORKING WITH QUERY STRINGS

3-query-string.html
// (A) NEW SEARCH PARAMS OBJECT
// ASSUMING THAT WE START WITH ?KEY=VAL&FOO=BAR
var params = new URLSearchParams(location.search);

// (B) HAS KEY & GET VALUE
console.log(params.has("key")); // true
console.log(params.get("key")); // val

// (C) LOOP THROUGH ALL KEYS
for (let k of params.keys()) {
  console.log(k); // key, foo
}

// (D) APPEND, SET, DELETE
params.append("hello", "world"); // query string is now key=val&foo=bar&hello=world
params.set("hello", "kitty"); // query string is now key=val&foo=bar&hello=kitty
params.delete("key"); // query string is now foo=bar&hello=kitty
 
// (E) TO STRING
var str = params.toString();
console.log(str); // foo=bar&hello=kitty

Lastly, we can also parse the search parameters into a new URLSearchParams(location.search) object. This will “expand” the functionality, and allow us to easily work with the query 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.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA 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.

 

EXTRA – PARSE URL FROM STRING OR HTML ELEMENTS

4-parse.html
<!-- (A) HTML ELEMENTS -->
<a id="demoA" href="https://code-boxx.com/path/file.html?key=val">Code Boxx</a>
<img id="demoB" src="baguette.png">
 
<script>
// (B) PARSE <A HREF>
let url = new URL(document.getElementById("demoA").href);
console.log(url.hostname); // code-boxx.com
console.log(url.pathname); // /path/file.html
 
// (C) PARSE <IMG SRC>
url = new URL(document.getElementById("demoB").src);
console.log(url.pathname); // /path/corgi.png
</script>

If you are not working with window.location, fear not. Simply parse the URL with new URL(URL STRING), and all the hostname pathname origin search etc... are still available.

 

REFERENCES & LINKS

 

INFOGRAPHIC CHEATSHEET

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

 

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 “Get URL Parts In Javascript (Host, Path, File, Query, ETC…)”

Leave a Comment

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