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;
}
console.log(getHost())

上面的实现了获取要求,下面介绍一下它的实现过程。

一.代码注释:

(1).function getHost(url) {},参数是一个url地址。

(2).if(typeof url == "undefined"|| null == url) {

  url = window.location.href;

},如果没有传递参数的话,那么就使用当前页面的url地址。

(3).var regex = /^\w+\:\/\/([^\/]*).*/,匹配一个域名地址。

(4).var match = url.match(regex),进行匹配操作。

(5).if(typeof match != "undefined" && null != match) {

  host = match[1];

},如果匹配不为空的话,那么就获取第一个字表达式所匹配的内容,比如一个url地址是http://www.pipipi.net/forum.php?mod=post,那么就是www.pipipi.net部分。

二.相关阅读:

(1).window.location.href可以参阅location.href属性一章节。

(2).match()可以参阅正则表达式match()函数一章节。

一线大厂高级前端编写,前端初中阶面试题,帮助初学者应聘,需要联系微信:javadudu

回复

我来回复
  • 暂无回复内容