在 Javascript 中获取 url 的最后一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10306003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the last part of an url in Javascript
提问by suchislife
Using the following URL example, how would I get the obtain the username from it?
使用以下 URL 示例,我将如何从中获取用户名?
http://www.mysite.com/username_here801
http://www.mysite.com/username_here801
A regex solution would be cool.
正则表达式解决方案会很酷。
The following sample only gets the domain name:
以下示例仅获取域名:
var url = $(location).attr('href');
alert(get_domain(url));
function get_domain(url) {
return url.match(/http:\/\/.*?\//);
}
jQuery solutions are also acceptable.
jQuery 解决方案也是可以接受的。
回答by Richard Dalton
var url = "http://www.mysite.com/username_here801";
var username = url.match(/username_(.+)/)[1];
To always return the text directly after the slash that follows the .com you can do this:
要始终在 .com 后面的斜杠之后直接返回文本,您可以执行以下操作:
var url = "http://www.mysite.com/username_here801";
var urlsplit = url.split("/");
var username = urlsplit[3];
回答by gabitzish
You can access it with document.location.pathname
你可以访问它 document.location.pathname
回答by Salman A
If a RegEx solution is acceptable, you could try:
如果可以接受 RegEx 解决方案,您可以尝试:
function get_path(url) {
// following regex extracts the path from URL
return url.replace(/^https?:\/\/[^\/]+\//i, "").replace(/\/$/, "");
}
回答by gabitzish
You could use your getDomain() function to find out where your pathname start.:
您可以使用 getDomain() 函数找出路径名的开始位置。:
function getUsername(url){
var position = getDomain(url).length + 1;
return url.slice(position);
}