Skip to main content

JavaScript Location Hostnames and URL Examples

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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: https://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: https:
 
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.

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn how Git works, and how to use it to streamline your workflow!


Google, Netflix and ILM are Python users. Maybe you should too?