该例子通过 location.hostname 属性得到 URL 中的主机名称和端口号:
假设当前页面的 URL 是:http://www.520mg.com/p-javascript_location.shtml
<script type="text/javascript"> document.write(location.hostname); </script>
运行该例子,输出:
www.520mg.com
该例子通过 location.hostname 属性来设置 URL 中的主机名:
假设当前页面的 URL 是:http://www.520mg.com/test.shtml
<html>
<script type="text/javascript">
function setHostname(){
    location.host = "localhost";
}
</script>
<body>
<button onclick="setHostname()">设定主机名</button>
</body>
</html>
运行该例子,点击 设定主机名 的超链接,触发 setHostname() 函数,浏览器地址栏的 URL 将变为:http://localhost/test.shtml,而浏览器也将访问该 URL。