[英]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]
@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.