JavaScript获取最后一个URL段

JavaScript获取最后一个URL段,javascript,Javascript,获取URL最后一段的最佳方式是什么(忽略任何参数)。此外,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.p

获取URL最后一段的最佳方式是什么(忽略任何参数)。此外,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答案非常有效。如果要执行相同的操作,但使用正则表达式,则可以按如下方式实现:

    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
    

    在我看来,上面的代码比使用拆分操作更高效、更干净。

    类似这样的操作?这两个操作的可能重复不考虑最后一个“/”字符。请看我贴的例子2