How to Get Current URL With jQuery
Let us say your web page’s current URL is the following
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.
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