JavaScript Location Hostnames and URL Examples
Share
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.