欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

javascript(JS)获取当前域名url程序代码

shiping1 的头像
js获取当前域名我们只要使用document.domain就可以直接获取当前页面的域名了,下面我整理了一些获取域名的例子,有需要的朋友可参考参考。
 

例子 document.domain

 代码如下复制代码

<script language="javascript">
//获取域名
host = window.location.host;
host2=document.domain;

//获取页面完整地址
url = window.location.href;

document.write("<br>host="+host)
document.write("<br>host2="+host2)
document.write("<br>url="+url)
</script>

方法二,利用url来解析域名

 代码如下复制代码

<script type="text/javascript">
function getHost(url)
{
    var host = "null";
    if(typeof url == "undefined"|| null == url) {
        url = window.location.href;
    }
    var regex = /^\w+\:\/\/([^\/]*).*/;
    var match = url.match(regex);
    if(typeof match != "undefined" && null != match) {
        host = match[1];
    }
    return host;
}
   
</script>

使用方法:

 代码如下复制代码

<script type="text/javascript">
  var url = 'http://www.111cn.net';
  alert(getHost(url));
</script>

补充

获取当前Url的4种方法

var url = window.location.href;

var url = self.location.href;

var url = document.URL;

var url = document.location;

1.获取当前完整网址
thisURL = document.URL;
thisHREF = document.location.href;
thisSLoc = self.location.href;
thisDLoc = document.location;
strwrite = ” thisURL: [" + thisURL + "]”
strwrite += ” thisHREF: [" + thisHREF + "]”
strwrite += ” thisSLoc: [" + thisSLoc + "]”
strwrite += ” thisDLoc: [" + thisDLoc + "]”
document.write( strwrite );

2.获取当前域名信息
thisTLoc = top.location.href;
thisPLoc = parent.document.location;
thisTHost = top.location.hostname;
thisHost = location.hostname;
strwrite = ” thisTLoc: [" + thisTLoc + "]”
strwrite += ” thisPLoc: [" + thisPLoc + "]”
strwrite += ” thisTHost: [" + thisTHost + "]”
strwrite += ” thisHost: [" + thisHost + "]”
document.write( strwrite );

3.获取当前页面
tmpHPage = thisHREF.split( “/” );
thisHPage = tmpHPage[ tmpHPage.length-1 ];
tmpUPage = thisURL.split( “/” );
thisUPage = tmpUPage[ tmpUPage.length-1 ];
strwrite = ” thisHPage: [" + thisHPage + "]”
strwrite += ” thisUPage: [" + thisUPage + "]”
document.write( strwrite );

location的属性介绍:
href 设置或获取整个 URL 为字符串。
search 设置或获取 href 属性中跟在问号后面的部分。
hash 设置或获取 href 属性中在井号“#”后面的部分。
protocol 设置或获取 URL 的协议部分。
host 设置或获取 location 或 URL 的 hostname 和 port 号码。
hostname 设置或获取 location 或 URL 的 hostname
port 设置或获取与 URL 关联的端口号码。
pathname 设置或获取对象指定的“文件名”或路径。

来自 http://www.111cn.net/wy/js-ajax/62834.htm
普通分类: