Get current URL with JavaScript/jQuery
This post will discuss how to get the current URL of the page in JavaScript and jQuery.
1. Using JavaScript
The Location object in JavaScript contains information about the current URL of the document. It can be accessed using the Window interface. So, you can use the Window.location to get the Location object for the current document. Then href property location.href can be used to get a string containing the full URL.
The Location object offers several other properties to get protocol, host, domain, port number, pathname, etc., of the URL. For example,
|
1 2 3 4 5 6 7 8 9 |
window.location.href // https://example.com:8080/get?post=123#selector window.location.protocol // https: window.location.host // example.com:8080 window.location.hostname // example.com window.location.port // 8080 window.location.pathname // /get window.location.search // ?post=123 window.location.hash // #selector window.location.origin // https://example.com:8080 |
Alternatively, you can access the Location object with the Document.location property of the Document interface. You can also use the document.URL or document.documentURI property to get the URL of the current document.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
document.location.href // https://example.com:8080/get?post=123#selector document.location.protocol // https: document.location.host // example.com:8080 document.location.hostname // example.com document.location.port // 8080 document.location.pathname // /get document.location.search // ?post=123 document.location.hash // #selector document.location.origin // https://example.com:8080 document.URL // https://example.com:8080/get?post=123#selector document.documentURI // https://example.com:8080/get?post=123#selector |
2. Using jQuery
With jQuery, you can use the .prop() or .attr() method to get properties of the location object, as shown below:
|
1 2 3 4 5 6 7 8 9 |
$(location).attr('href'); // https://example.com:8080/get?post=123#selector $(location).attr('protocol'); // https: $(location).attr('host'); // example.com:8080 $(location).attr('hostname'); // example.com $(location).attr('port'); // 8080 $(location).attr('pathname'); // /get $(location).attr('search'); // ?post=123 $(location).attr('hash'); // #selector $(location).attr('origin'); // https://example.com:8080 |
That’s all about getting the current URL in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)