Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last part of an url in Javascript

Using the following URL example, how would I get the obtain the username from it?

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.

like image 776
suchislife Avatar asked Dec 16 '22 01:12

suchislife


2 Answers

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

http://jsfiddle.net/5LHFd/

To always return the text directly after the slash that follows the .com you can do this:

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

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

like image 157
Richard Dalton Avatar answered Jan 11 '23 23:01

Richard Dalton


You can access it with document.location.pathname

like image 29
gabitzish Avatar answered Jan 11 '23 22:01

gabitzish