[英]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: 说明:
Location.pathname
is a string containing an initial '/'
followed by the path of the URL . Location.pathname
是一个字符串,包含一个首字母'/'
后跟URL的路径 。 String.prototype.match(regexp)
returns an array of the matches. String.prototype.match(regexp)
返回匹配数组。 [^/]*
matches anything but a slash , and that zero or more times . [^/]*
匹配除斜线之外的任何东西 ,并且零次或多次 。 (?=\\/*$)
matches a slash zero or more times at the end of the string , while not including it . (?=\\/*$)
在字符串末尾匹配斜杠零次或多次, 而不包括它 。 [0]
. [0]
检索它。 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.