Search

Friday, September 2, 2011

Get URL, URL part, URL parameters using javascript

Getting URL or URL parts through javascript is so easy. We can get protocal using this code :
	var proto    = window.location.protocol;
	alert( proto );

this code return "http:" protocol.
If you want to get host name from the URL using javascript then you can simple write this code:
	var hostName = window.location.host;
	alert( hostName );


this code return the host name like if you are running this code in local host then it returns "localhost"
if you want to get path of the URL with javascript then use this:
	var pathName = window.location.pathname;
	alert( pathName );


this code returns the path name of the current running script like you are running the script in test.html the it return the full path name with filename test.html
Or if you want to get parameter used in URL with javascript then simply do this:
	var params   = window.location.search;
	alert( params );


it returns the parameter used in the URL

now lets join all the code :
	var proto    = window.location.protocol;
	var hostName = window.location.host;
	var pathName = window.location.pathname;
	var params   = window.location.search;

	alert( proto + hostName + pathName + params );


1 comment:

Virendra said...

Another easy to do the same thing..

function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
Reference : http://jquerybyexample.blogspot.com/2012/06/get-url-parameters-using-jquery.html

Related Posts Plugin for WordPress, Blogger...