Reputation: 4408
Let's say I have the following url:
something.com/messages/username/id
How can I get the username
or id
?
Upvotes: 1
Views: 2509
Reputation: 29991
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
Upvotes: 3
Reputation: 22728
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;
};
Upvotes: 3
Reputation: 33865
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];
Upvotes: 4
Reputation: 95288
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]);
Upvotes: 8