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.

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

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