取得當前頁面的檔名,在前端互動中經常派上用場,例如依頁面名稱載入對應的側欄或樣式。程式碼非常短。

核心就是對 location.pathname 做字串切割:
var path = location.pathname;
var fileName = path.substring(path.lastIndexOf("/") + 1);
alert(fileName);
若連查詢參數也一併去掉,可以再加一段處理:
var fileName = path.substring(path.lastIndexOf("/") + 1).replace(/\?.*$/, '');
範例中為了方便看結果用了 alert 彈窗,實際使用時把值指派給變數即可。若網址結尾是斜線(例如 /news/),上面的寫法會得到空字串,這時可以改用 location.href 搭配更完整的判斷。
現代瀏覽器也提供了更直接的 API:
var fileName = location.pathname.split('/').pop();