Reputation: 105
i try to get values of a url with anchor like this: http://website/list/#/genre/song
It is in jquery because after i get the values, i have to edit html tags contents.
I retrieve hash value with:
var hash = window.location.hash.substring(1);
I have 2 variables:
var genre;
var song;
the problem is that there may be 2 possibilities in the url:
http://website/list/#/genre
or http://website/list/#/genre/
or
http://website/list/#/genre/song
or http://website/list/#/genre/song/
if we are in case 1, i would have 'genre' value from hash variable
if we are in case 2, i would have 'genre' and 'song' values from hash variable
my jquery function is actually simple:
$(function(){
var hash = window.location.hash.substring(1);
var url_parts = hash.replace(/\/\s*$/,'').split('/');
console.log("result: "+url_parts);
});
I do not know how to consider the two cases. Actually i just get a full string.
And if i try http://website/list/#/genre/
, the result is:
result: ,genre
can you help me?
Upvotes: 1
Views: 1219
Reputation: 781210
Test whether a particular index exists after splitting:
$(function(){
var hash = window.location.hash.substring(1);
var url_parts = hash.replace(/\/\s*$/,'').split('/');
genre = url_parts.length >= 2 ? url_parts[1] : '';
song = url_parts.length >= 3 ? url_parts[2] : '';
console.log("result: "+url_parts);
});
Upvotes: 1