Home » Javascript, jQuery

get URL or current page url as parts in jquery

10 August 2012 No Comment
Share on Facebook

We might have wanted to get URL of the current page in jQuery or to manipulate parts of the current page URL in jQuery. In this article we will discuss how to get URL of current page in jquery and also how to get parts of the url in jquery.

Tutorial difficulty:

  • Basic users
  • used: jQuery, HTML

In this article we will access the url of the current page using location object, location.href property holds the current page URL.

Window Location Object:

Each page path or the URL is referenced in window.location.href property, The location Objects also holds

location.protocol, location.host & location.pathname : the parts of the URL

We can access the full path from

location.href : Full path or URL

Let us see how to use them in jquery code.

Get URL of current page path:

As we have seen above we are going to see how to access location object.

$().ready(function()
{
	alert($(location).attr('href'));
}

Here, we are accessing the location.href to get page url in jquery.

Access current page URL using document.URL

$().ready(function()
{

	alert($(document).attr('URL'));

}

Above is again simple code to get full path of the browser-URL.

Get parts of URL in jQuery:

$().ready(function()
{
	alert($(location).attr('protocol'));
	alert($(location).attr('host'));
	alert($(location).attr('pathname'));
});
Example URL: http://designscripting.com/jquery/url.html

The Output will be:

protocol: “http”
host: “designscripting.com”
pathname: “jquery/url.html”

Conclusion:

We have discussed how to access the page URL and URL parts in jquery. Download source to get the example files.

GET THE UPDATES VIA EMAIL

We don't share your email anywhere, grab our rss via feedburner