Site icon MoreOnFew

How to get current url in JavaScript?

Javascript on MoreOnFew.com

Javascript on MoreOnFew.com

JavaScript has come a long way since its inception. I remember the days when it was mainly used only for form validations. Now we use JavaScript for a lot more functionalities. JavaScript has a vast number of APIs which enables us to access a variety of features and information from the browser. One such API is the window.location API which helps us to get current URL in javascript.

Get current URL in Javascript using window.location object

Getting the current URL in JavaScript is quite simple using the window.location object. You can get the current URL in javascript using the following code

window.location.href 
// https://www.moreonfew.com/how-to-get-current-url-in-javascript/

Using the JavaScript object window.location.href, you can get the current full URL of the page. It would return you the URL of the current page with the protocol (“https”), the domain (“www.moreonfew.com”), and the path plus the filename (“how-to-get-current-url-in-javascript”). It would also return the query parameters in the URL if they are present. In this current page’s URL there aren’t any query parameters and hence we did not get it.

How to get current URL in JQuery?

If you are using jQuery and would like to get the current URL, then you can use the following code

$(location).attr('href');
// OR
$(location).prop('href');

// https://www.moreonfew.com/how-to-get-current-url-in-javascript/

If you notice, in jQuery too, we need to access the “location” object in order to get the current URL. Once we access the location object, we use the “attr” or “prop” API to get the “href” attribute’s value.

However, I would suggest that it’s better to use window.location.href as it would be comparatively faster and simpler too.

I hope that you enjoyed reading about the method to get current URL in JavaScript. As you noticed, the way to get current URL in jQuery is also very similar and the “location” object is what we need to tap into even in the case of jQuery. If you liked this article, you can find more JavaScript articles under our JavaScript section.