简体   繁体   English

最后使用/获取网址的最后一部分

[英]Get last part of url with / at the end

I'm trying to get the last part of this url: 我正在尝试获取此网址的最后一部分:

http://webserver/Foo/login/

the code that I wrote: 我写的代码:

var location = window.location.href.split('/').pop();

will return an empty string 'cause after the / there is nothing. 将返回一个空字符串'因为/什么都没有。 I need to get at least the previous part, so in this case, login. 我需要至少获得前一部分,所以在这种情况下,登录。

How can I do this? 我怎样才能做到这一点?

The solution using String.replace() (used to replace possible / at the end of the string) and String.split() functions: 使用String.replace() (用于替换字符串末尾的可能/ )和String.split()函数的解决方案:

 var url = 'http://webserver/Foo/login/', last_section = url.replace(/\\/+$/, '').split('/').pop(); console.log(last_section); 

 const getLastPartURL = url => { const parts = url.split('/'); const length = parts.length; return parts[length - 1] == '' ? parts[length - 2] : parts[length - 1] } console.log(getLastPartURL('http://webserver/Foo/login/')) console.log(getLastPartURL('http://webserver/Foo/login')) console.log(getLastPartURL('http://webserver/Foo/')) console.log(getLastPartURL('http://webserver/Foo')) 

This should do the trick: 这应该做的伎俩:

location.pathname.match(/[^/]*(?=\/*$)/)[0]

Explanation: 说明:

Example: 例:

For all these URLs the output is login : 对于所有这些URL,输出是login

  • http://webserver/Foo/login
  • http://webserver/Foo/login/
  • http://webserver/Foo/login//

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

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