JavaScript
Article
By Sam Deering

JavaScript Location Hostnames and URL Examples

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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.

--ADVERTISEMENT--

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?