DIV CSS 佈局教程網

用 a 標籤解析 URL:一個函數搞定網址拆解
編輯:關於JavaScript     

處理網址時,我們通常會想到 window.location,它現成提供了 protocol、hostname、host、port、pathname、search、hash 等欄位。但很多人不知道,用 document.createElement('a') 做出來的 a 標籤,只要指定 href,就會自動具備幾乎相同的屬性——這讓我們不必寫一堆正則表達式,也能把任意字串形式的網址拆得乾乾淨淨。

function parseURL(url) {
  var a = document.createElement('a');
  a.href = url;
  return {
    source: url,
    protocol: a.protocol.replace(':',''),
    host: a.hostname,
    port: a.port || '80',
    query: a.search,
    params: (function(){
      var ret = {}, seg = a.search.replace(/^\?/,'').split('&'),
          len = seg.length, i = 0, s;
      for (; i < len; i++) {
        if (!seg[i]) { continue; }
        s = seg[i].split('=');
        ret[s[0]] = s[1];
      }
      return ret;
    })(),
    file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
    hash: a.hash.replace('#',''),
    path: a.pathname.replace(/^([^\/])/,'/$1'),
    relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
    segments: a.pathname.replace(/^\//,'').split('/')
  };
}

實測一次

console.log(parseURL("https://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2"));

輸出結果:

{
  file: "dom_obj_anchor.asp",
  hash: "id2",
  host: "www.w3school.com.cn",
  params: { type: "2" },
  path: "/jsref/dom_obj_anchor.asp",
  port: "80",
  protocol: "http",
  query: "?type=2",
  relative: "/jsref/dom_obj_anchor.asp?type=2#id2",
  segments: ["jsref", "dom_obj_anchor.asp"],
  source: "https://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2"
}

為什麼這招好用

因為瀏覽器在設定 href 的瞬間就已經幫你做完標準化的解析工作,包括補上預設連接埠、處理相對路徑、分離 query 與 hash。相對於自己刻正則,這種做法更短、更不容易出錯,也天然相容各種邊界情況。

要注意的是,query 的字串在這裡只做了最簡單的切割,若參數值本身含有編碼過的等號或 &,建議改用 decodeURIComponent 逐項處理,或直接採用 URLSearchParams。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved