js獲取主機域名程式碼例項

antzone發表於2017-04-06

本章節分享一段程式碼例項,它實現了獲取主機域名效果。

程式碼如下:

[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).var host = "null",宣告一個變數並賦初值為字串null。(3).if(typeof url == undefined|| null == url) {

  url = window.location.href;

},如果沒有傳遞url引數。

(4).var regex = /^\w+\:\/\/([^\/]*).*/,此正規表示式可以匹配域名。

(5).var match = url.match(regex),進行匹配。

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

  host = match[1];

},如果匹配成功,也就是獲取了相關值,那麼就獲取域名。

二.相關閱讀:

(1).window.location.href可以參閱location.href屬性一章節。

(2).match()可以參閱正規表示式match()函式一章節。

相關文章