JavaScript
Article

JavaScript Location Hostnames and URL Examples

By Sam Deering

Simple JavaScript code snippets to manipulate location URLs (you know that weird thing in the address bar!) to get the host, hostname, pathname, protocol, port and the regular expression to check if a string is a hostname.

console.log(window.location.href);
//output: http://www.jquery4u.com/javascript/javascript-location-hostnames-url-examples/

console.log(window.location.hostname);
//output: www.jquery4u.com
 
console.log(window.location.host);
//output: www.jquery4u.com
 
console.log(window.location.pathname);
//output: /javascript/javascript-location-hostnames-url-examples/
 
console.log(window.location.protocol);
//output: http:
 
console.log(window.location.port);
//output: (an empty string)
 
//regular expression to check if a string is a hostname.
console.log(window.location.hostname.match(/^.*?-?(w*)./)[1]);
//output: www

Tip: If you just type in window.location into firebug you can analyse all of the above.

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

No Reader comments

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.