在 Javascript 中获取 url 的最后一部分

Get the last part of an url in Javascript

本文关键字:最后 一部分 url 获取 Javascript      更新时间:2023-09-26

使用以下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访问它

如果正则表达式解决方案可以接受,您可以尝试:

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); 
}