紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

[JS] Javascript 取得網址目前頁面路徑:location.pathname 用法、路由拆解與選單高亮實作

[JS] Javascript 取得網址目前頁面路徑:location.pathname 用法、路由拆解與選單高亮實作 特色圖片

想要用 JavaScript 取得網址目前 URL 中的頁面路徑(Path),最直接的標準屬性是 window.location.pathname。location.pathname 會回傳從根目錄斜線 / 開始的路徑與頁面名稱,且自動排除前方的網域名稱(Domain)以及後方的 GET 查詢參數(?search)與錨點(#hash),非常適合用於前端路由判斷與導覽列選單狀態比對。

⚡ 快速跳轉(依實務情境選擇):

基本語法:使用 location.pathname 取得目前頁面路徑

假設當前網址為:

https://www.seanacnet.com:8080/js/location-pathname.html?id=111&t=9#template

使用範例:

let path = window.location.pathname;

console.log(path);
// 輸出: "/js/location-pathname.html"

注意:即使當前處於網站首頁(例如 https://www.seanacnet.com),location.pathname 也不會回傳空字串,而是固定回傳根斜線 "/"。

實務場景一:拆解路由層級陣列與取得最後一層頁面名稱

在 RESTful 路由或靜態網站架構中(例如網址路徑為 /products/electronics/laptop-15 或 /js/location-pathname.html),我們常需要將路徑依 / 拆解為陣列,以提取分類層級或最後一段 Slug/檔案名稱。

由於 location.pathname 開頭必有一個 /(且部分網址結尾也有 /),直接執行 .split('/') 會在陣列頭尾產生空字串 ""。建議搭配 .filter(Boolean) 清除空元素:

// 假設當前路徑為 "/products/electronics/laptop-15/"
const rawPath = window.location.pathname;

// 1. 拆解為乾淨的路由層級陣列(自動濾除頭尾斜線產生的空字串)
const segments = rawPath.split('/').filter(Boolean);
console.log(segments);
// 輸出: ["products", "electronics", "laptop-15"]

// 2. 取得第一層主分類與最後一層頁面代稱 (Slug / 檔名)
const mainCategory = segments[0] || '';      // "products"
const currentSlug  = segments.at(-1) || '';  // "laptop-15"

在傳統多頁式網站(MPA)或 WordPress 主題開發中,常需要根據目前頁面路徑,自動為頂部導覽列(Navbar)對應的 <a> 連結加上 .active 樣式。

透過比對超連結元素內建的 link.pathname 與 window.location.pathname,即可免除繁瑣的完整網址字串裁切:

function highlightActiveNavLinks() {
  // 統一移除結尾多餘斜線(但保留首頁 "/"),避免 "/about/" 與 "/about" 比對失敗
  const normalizePath = (p) => (p.length > 1 ? p.replace(/\/+$/, '') : p);
  const currentPath = normalizePath(window.location.pathname);

  document.querySelectorAll('.navbar a[href]').forEach((link) => {
    // 僅比對同網域的站內連結
    if (link.hostname !== window.location.hostname) return;

    const linkPath = normalizePath(link.pathname);

    // 完全相等,或屬於該主分類下的子頁面(排除首頁 "/" 誤判所有路徑)
    const isMatched =
      currentPath === linkPath ||
      (linkPath !== '/' && currentPath.startsWith(`${linkPath}/`));

    if (isMatched) {
      link.classList.add('active');
      link.setAttribute('aria-current', 'page');
    }
  });
}

常見問題排查:結尾斜線(Trailing Slash)與中文路徑解碼

Q1:為什麼網址路徑含有中文時,location.pathname 會顯示 %E4%B8%AD... 亂碼?

  • 問題原因:根據標準 URL 規範,瀏覽器會自動將路徑中的非 ASCII 字元(如中文字或空白)轉為 Percent-encoding(百分比編碼)。
  • 解法:若需將路徑名稱顯示於麵包屑導覽或畫面上,請外包一層 decodeURIComponent():
    const readablePath = decodeURIComponent(window.location.pathname);

Q2:location.pathname 會包含 ?id=111 參數或 #hash 錨點嗎?

  • 不會。location.pathname 僅包含路徑區段。若需一併取得完整「路徑 + GET 參數 + 錨點」,可組合使用:
    const fullRelativeUrl = location.pathname + location.search + location.hash;

要查看 location.pathname 在各個瀏覽器的相容性,請參考:MDN Web Docs: Location.pathname 瀏覽器相容性。

如果你還想進一步了解 JS 取得 URL 的其他參數,可前往以下專篇查詢:

發表迴響