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

Javascript

如何透過 Javascript 取得網址與 URL 相關參數:location 物件與 new URL() 解析教學

如何透過 Javascript 取得網址與 URL 相關參數:location 物件與 new URL() 解析教學 特色圖片

現今網站製作隨著前後端分離架構普及,學習如何透過 Javascript 取得網址與解析 URL 相關參數,是前端處理路由判斷、篩選器狀態同步與 API 串接的核心基本功。在實務開發中,我們會依據「要讀取的是當前瀏覽器網址,還是外部傳入的任意 URL 字串」,分別選用 window.location 或現代原生 new URL() 建構子。

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

情境一:讀取當前瀏覽器頁面的網址與參數(window.location 導覽)

如果你只需要直接取得「使用者目前正在瀏覽的網頁網址」及其各部位參數,瀏覽器已將所有資訊封裝在全域的 window.location 物件中:

// 一行程式碼取得當前頁面各項網址資訊
const currentUrl  = window.location.href;     // 完整網址
const currentHost = window.location.hostname; // 純網域名稱 (不含連接埠)
const currentPath = window.location.pathname; // 頁面路徑 (如 "/products/list")
const queryString = window.location.search;   // GET 參數字串 (如 "?page=2&sort=asc")
const hashAnchor  = window.location.hash;     // 錨點名稱 (如 "#section-1")

針對 location 物件旗下的 9 個標準屬性,我們整理了獨立的實作範例與常見踩坑排查專篇,需要深入特定屬性時可直接點選查閱:

情境二:解析任意 URL 字串與讀取 GET 參數(new URL + URLSearchParams)

在實務專案中,我們經常拿到的不是當前頁面的網址,而是「從後端 API 回傳的目標連結」、「使用者在表單輸入的網址」或「超連結 <a> 上的 href 字串」。

此時若用正規表達式(RegExp)或 split() 手動切割字串非常容易出錯;標準做法是使用瀏覽器內建的 new URL(urlString) 建構子。它擁有與 window.location 完全相同的 9 大屬性,且內建 searchParams(URLSearchParams 實例)可直接讀取參數:

const targetUrlStr = 'https://www.seanacnet.com:8080/shop/items?category=book&page=3#reviews';

// 使用 try...catch 防範傳入非合法 URL 字串時拋出 TypeError
try {
  const parsedUrl = new URL(targetUrlStr);

  console.log(parsedUrl.origin);   // "https://www.seanacnet.com:8080"
  console.log(parsedUrl.hostname); // "www.seanacnet.com"
  console.log(parsedUrl.pathname); // "/shop/items"
  console.log(parsedUrl.hash);     // "#reviews"

  // 直接透過內建的 searchParams 取得特定 GET 參數值
  console.log(parsedUrl.searchParams.get('category')); // "book"
  console.log(parsedUrl.searchParams.get('page'));     // "3"
} catch (err) {
  console.error('傳入的網址格式無效:', err.message);
}

支援相對路徑解析(搭配第二個參數 base)

若待解析的字串是相對路徑(例如 "/api/v1/users?active=true"),只需將 window.location.origin 作為第二個基準參數傳入 new URL(relativePath, base),即可安全轉換為完整 URL 物件:

const apiEndpoint = new URL('/api/v1/users?active=true', window.location.origin);
console.log(apiEndpoint.href);
// 於 https://seanacnet.com 執行輸出: "https://seanacnet.com/api/v1/users?active=true"

情境三:動態新增、修改網址參數且不刷新頁面(history.replaceState)

在製作商品列表篩選器、分頁切換或頁籤(Tabs)時,我們常希望「當使用者點擊篩選條件時,同步更新瀏覽器網址列上的 ?page=2&tag=js 參數(方便使用者複製分享網址),但不要觸發整頁重新整理」。

注意:若直接修改 window.location.search = '?page=2',瀏覽器會強制重新載入整個網頁!若要維持單頁流暢體驗,應結合 new URL(window.location.href) 與 window.history.replaceState():

function updateUrlQueryParam(key, value) {
  // 1. 以當前頁面網址建立可編輯的 URL 實例
  const url = new URL(window.location.href);

  // 2. 新增、更新或刪除指定 GET 參數(自動處理 URI 編碼)
  if (value === null || value === undefined || value === '') {
    url.searchParams.delete(key);
  } else {
    url.searchParams.set(key, String(value));
  }

  // 3. 透過 History API 靜默更新網址列,不觸發網頁重新載入
  window.history.replaceState({}, '', url.toString());
}

// 範例:將網址列的 page 參數更新為 2,並移除空的 keyword 參數
updateUrlQueryParam('page', 2);
updateUrlQueryParam('keyword', '');

在開始使用前,若需確認各項屬性於不同瀏覽器環境的支援度,可參考以下 MDN 官方規格文件:

發表迴響