1

Let's say I have the following url:

something.com/messages/username/id

How can I get the username or id?

Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
Linas
  • 4,380
  • 17
  • 69
  • 117
  • You can split, like the other guys explained, but becareful with URLs having a bar as last character, then the split would return an empty string as the last item. To remove it (if exists), you can use MYSTRING.replace(/\/$/, ''); – Eliseu Monar dos Santos Feb 11 '12 at 16:30
  • @EliseuMonar: You can simply use positive indexing (from the beginning). What's the problem? All the solutions I see here also work if the URL has a slash at the end. – Niklas B. Feb 11 '12 at 16:43

4 Answers4

8

You can use String.split for that:

var parts = window.location.href.split('/'); # => ["http:", "", "something.com", "messages", "username", "id"]
var username = parts[4];
var id = parseInt(parts[5]);
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
4

I guess you could use the window.location.href to get the URL and then string.split() the URL on /.

var urlParts = window.location.href.split("/");
var username = urlParts[4];
var id = urlParts[5];
Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
3

You could split your url on every '/' character like this:

var url = "something.com/messages/username/id"; 
var array = url.split('/');
// array[2] contains username and array[3] contains id
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
3

I actually just had to deal with the other day. When you're accessing the cached version of some of our pages, the query string is actually part of the URL path. But if you're trying to avoid the cache, you use a query string.

Given one of the answers from How to get the value from the GET parameters? here's what I'm using to partially normalize access.

The router that takes the response does _.isArray() (we're built on top of backbone, so we have underscore available) and handles pulling the data out of the object or array in a different manner.

The slice at the end gets rid of the two "" since we're not using documents, just directories and our URLs start and end with /. If you're looking for document access, you should alter the slice accordingly.

var qs = function(){
    if(window.location.search){
        var query_string = {};            
        (function () {
            var e,
                a = /\+/g,  // Regex for replacing addition symbol with a space
                r = /([^&=]+)=?([^&]*)/g,
                d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                q = window.location.search.substring(1);

            while (e = r.exec(q)){
               query_string[d(e[1])] = d(e[2]);
            }
        })();
    } else {
        return window.location.pathname.split('/').slice(1, -1);
    }
    return query_string;
};
Community
  • 1
  • 1
tkone
  • 22,092
  • 5
  • 54
  • 78