简体   繁体   English

JavaScript获取最后一个URL段

[英]JavaScript get last URL segment

What is the best way to get the Last segment of the URL (omitting any parameters). 获取URL的最后一个段的最佳方法是什么(忽略任何参数)。 Also url may or may not include the last '/' character 网址也可以包含或不包含最后一个'/'字符

for example 例如

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

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

I've tried this but i can't get how to check for the last / 我已经尝试过了,但是我不知道如何检查最后一个/

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

Maybe something like? 也许像?

window.location.pathname.split('?')[0].split('/').filter(function (i) { return i !== ""}).slice(-1)[0]
  1. Split on '?' 分割为“?” to throw out any query string parameters 抛出任何查询字符串参数
  2. Get the first of those splits 获取这些拆分中的第一个
  3. Split on '/'. 在'/'上分割。
  4. For all those splits, filter away all the empty strings 对于所有这些拆分,请过滤掉所有空字符串
  5. Get the last one remaining 获取剩余的最后一个

@psantiago answer works great. @psantiago答案很好用。 If you want to do the same but using RegEx you can implement as follows: 如果要执行相同操作但使用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

In my opinion, the above code is more efficient and cleaner than using split operations. 我认为,上述代码比使用拆分操作更有效,更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM