DIV CSS 佈局教程網

用 JavaScript 取得當前頁面名稱的兩種寫法
編輯:JavaScript綜合知識     

需要知道使用者目前停留在哪個頁面的時候,直接從 location.href 拆解即可。以下提供兩個函式,一個帶副檔名,一個不帶。

寫法一:不含副檔名的頁面名稱

// 取當前頁面名稱(不帶後綴名)
function getPageName1() {
  var a = location.href;
  var b = a.split("/");
  var c = b.slice(b.length - 1, b.length).toString().split(".");
  return c.slice(0, 1);
}

寫法二:含副檔名的頁面名稱

// 取當前頁面名稱(帶後綴名)
function getPageName2() {
  var strUrl = location.href;
  var arrUrl = strUrl.split("/");
  var strPage = arrUrl[arrUrl.length - 1];
  return strPage;
}

原理與注意事項

兩段程式都是先以斜線切開網址,取最後一段就是檔名;差別只在寫法一多再用句點切一次,丟掉副檔名部分。

要留意的是,寫法一取的是 location.href 而不是 location.pathname,所以如果網址帶有查詢參數(例如 page.html?id=5),回傳結果會是 page 還算幸運,但寫法二會把 page.html?id=5 整串都當成檔名回傳。此外,若使用者開啟的是目錄路徑(例如 https://example.com/blog/),最後一段會是空字串。

更穩健的現代寫法是直接用 location.pathname 搭配正則:

// 帶副檔名
const withExt = location.pathname.split("/").pop();

// 不帶副檔名
const noExt = withExt.replace(/\.[^.]+$/, "");

另外提醒,getPageName1() 的最後是 c.slice(0, 1),回傳的是「陣列」而非字串,若要直接比對或拼接,記得加上 [0] 或 .toString()。

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