In this article, you’ll learn how to get URL and URL parts such as hostname, pathname, query, hash, etc. in javascript. There is a property of the built-in window.location
object that will provide that for the current window which includes hostname, query-string, fragment identifier, etc. The window.location
object can be written without the window prefix.
Variable |
Description |
|
This will give you the full URL. http://www.exampledomain.com/account/search?filter=a#top |
|
Contains the protocol. http://www.exampledomain.com/account/search?filter=a#top |
|
Contains the hostname. http://www.exampledomain.com/account/search?filter=a#top |
|
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://www.exampledomain.com:8080/account/search?filter=a#top |
|
Contains the protocol, hostname, and port. http://www.exampledomain.com:8080/account/search?filter=a#top |
|
Contains the port number. http://www.exampledomain.com:8080/account/search?filter=a#top |
|
Contains the path and file name. http://www.exampledomain.com:8080/account/search?filter=a#top |
|
Contains the query string or parameter. http://www.exampledomain.com:8080/account/search?filter=a |
|
Contains the hash anchor. http://www.exampledomain.com:8080/account/search?#top |
Here is an example to get URL and URL parts such as hostname, pathname, query, hash in javascript.
// If URL is http://www.exampledomain.com/account/search?filter=a#top
console.log(window.location.pathname); // /account/search
// For reference:
console.log(window.location.host); // www.exampledomain.com (includes port if there is one)
console.log(window.location.hostname); // www.exampledomain.com
console.log(window.location.hash); // #top
console.log(window.location.href); // http://www.exampledomain.com/account/search?filter=a#top
console.log(window.location.port); // (empty string)
console.log(window.location.protocol); // http:
console.log(window.location.search); // ?filter=a
If you have an abstract URL string (not from the current window.location
), you can use this trick also:
var el = document.createElement('a');
el.href = "http://www.exampledomain.com/account/search?filter=a#top";
console.log(el.host); // www.somedomain.com (includes port if there is one[1])
console.log(el.hostname); // www.somedomain.com
console.log(el.hash); // #top
console.log(el.href); // http://www.somedomain.com/account/search?filter=a#top
console.log(el.pathname); // /account/search
console.log(el.port); // (port if there is one[1])
console.log(el.protocol); // http:
console.log(el.search); // ?filter=a
I hope this article will help you to understand how to get URL and URL parts such as hostname, pathname, query, hash, etc. in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments