get current url in jquery javascript

How to Get Current URL With jQuery

Often web developers need to retrieve current URL of web pages using jQuery. Actually you don’t need jQuery to get current URL as it can be easily obtained using plain JavaScript. JS offers many useful properties to not only get current URL but also different parts of URL. In this article, we will learn how to get current URL with jQuery.

How to Get Current URL With jQuery

Let us say your web page’s current URL is the following

https://www.example.com/products/page.html

Here are 3 simple readymade properties to easily obtain current URLs and its parts.

var pathname = window.location.pathname; // Returns path only (/products/page.html)
var url      = window.location.href;     // Returns full URL (https://www.example.com/products/page.html)
var origin   = window.location.origin;   // Returns base URL (https://www.example.com)

As you can see, JS already provides pre-defined objects and properties to store current URL and its parts.

On the other hand, if you really want to use jQuery only to get current URL, you can use $(location) instead of window.location above. Also, you need to use hostname instead of origin property used above.

$(location).attr('href');      // https://www.example.com/products/page.html
$(location).attr('pathname');  // /products/page.html
$(location).attr('hostname');      // https://www.example.com

In this article, we have learnt how to get current URL with jQuery.

Also read:

How to Get Class List for DOM Element
How to Move Element Into Another Element in jQuery
How to Automatically Scroll to Bottom of Page in JS
How to Change Image Source in jQuery
How to Check for Hash in URL Using jQuery

Leave a Reply

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