簡體   English   中英

JavaScript獲取最后一個URL段

[英]JavaScript get last URL segment

獲取URL的最后一個段的最佳方法是什么(忽略任何參數)。 網址也可以包含或不包含最后一個'/'字符

例如

http://Home/Billing/Index.html?param1=2&another=2
should result in: Index.html

http://Home/Billing/Index.html/
should result in: Index.html

我已經嘗試過了,但是我不知道如何檢查最后一個/

ar href = window.location.pathname;
            var value = href.lastIndexOf('/') + 1);

也許像?

window.location.pathname.split('?')[0].split('/').filter(function (i) { return i !== ""}).slice(-1)[0]
  1. 分割為“?” 拋出任何查詢字符串參數
  2. 獲取這些拆分中的第一個
  3. 在'/'上分割。
  4. 對於所有這些拆分,請過濾掉所有空字符串
  5. 獲取剩余的最后一個

@psantiago答案很好用。 如果要執行相同操作但使用RegEx,則可以執行以下操作:

var r = /(\/([A-Za-z0-9\.]+)(\??|\/?|$))+/;
r.exec("http://Home/Billing/Index.html?param1=2&another=2")[2]; //outputs: Index.html 
r.exec("http://Home/Billing/Index.html/"); //outputs: Index.html

我認為,上述代碼比使用拆分操作更有效,更干凈。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM