如何使用Javascript获取一个链接地址中的顶级域名

JavaScript04

如何使用Javascript获取一个链接地址中的顶级域名,第1张

<a id="a1" href="http://www.lingchenliang.com/tags-189.html" target="_blank">JS特效</a>

<script language="javascript">

alert(getdomain(1,'a1')) //弹窗输出域名

function getdomain(typ,id){ //参数:类型(0:当前域名,1:顶级域名),链接对象ID

var url=window.document.getElementById(id).href //获取链接

if(typ==0){ //获取当前域名,如:www.lingchenliang.com

var a = document.createElement('a')

a.href = url

url=a.hostname

}else{ //获取顶级域名,如:lingchenliang.com

//使用正则表达式

url=url.replace(/.+[\.\/]([A-z]+\.[A-z]+)\/[^\/].+/,"$1")

}

return url //返回域名值

}

</script>

今天给各位朋友介绍两种js获取当前域名

代码如下

//获取当前域名

1、window.location.host

2、document.domain

//获取当前页面地址

url

=

window.location.href

例子

代码如下

<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="+ur(www.45it.net)l)

</script>

补充:

获取当前域名信息

代码如下

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

)