繁体   English   中英

在Javascript中获取网址的最后一部分

[英]Get the last part of an url in Javascript

使用以下URL示例,我如何从中获取用户名?

http://www.mysite.com/username_here801

正则表达式解决方案很酷。

以下示例仅获取域名:

  var url = $(location).attr('href');

  alert(get_domain(url));

  function get_domain(url) {
    return url.match(/http:\/\/.*?\//);
  }

jQuery解决方案也是可以接受的。

var url = "http://www.mysite.com/username_here801";    
var username = url.match(/username_(.+)/)[1];

http://jsfiddle.net/5LHFd/

要始终在.com后面的斜杠后直接返回文本,您可以这样做:

var url = "http://www.mysite.com/username_here801";
var urlsplit = url.split("/");
var username = urlsplit[3];

http://jsfiddle.net/5LHFd/2/

您可以使用document.location.pathname访问它

如果可以接受RegEx解决方案,您可以尝试:

function get_path(url) {
    // following regex extracts the path from URL
    return url.replace(/^https?:\/\/[^\/]+\//i, "").replace(/\/$/, "");
}

您可以使用getDomain()函数找出路径名的起始位置:

function getUsername(url){
   var position = getDomain(url).length + 1;
   return url.slice(position); 
}

暂无
暂无

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

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