article

Wednesday, April 30, 2014

Get URL and URL Parts in JavaScript

Get URL and URL Parts in JavaScript
 
JavaScript can access the current URL

http://tutorial101.blogspot.com/example/currenturl

window.location.protocol = "http"
window.location.host = "tutorial101.blogspot.com"
window.location.pathname = "example/currenturl"

full URL path in JavaScript:
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

breath up the pathname, for example a URL like http://tutorial101.blogspot.com/example/currenturl, you can split the string on "/" characters
<script>
 var pathArray = window.location.pathname.split( '/' );
 var secondLevelLocation = pathArray[2]; //access the different parts by the parts of the array
 alert(secondLevelLocation); //results = currenturl
 </script>

Related Post