get many #hash values in url (anchor) in jquery

325
November 22, 2016, at 09:16 AM

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:

  1. http://website/list/#/genre or http://website/list/#/genre/

or

  1. 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?

Answer 1

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);
 });
READ ALSO
change color of items one by one

change color of items one by one

I wrote a script that creates a set of smaller circles arranged in a circle, which are added to the DOM one by one with a loop. After first loop is done (so I would expected this to be when i == 54) I would like to start another loop, starting from the first circle...

251
jqgrid: how best to handle the effects of showing/hiding columns

jqgrid: how best to handle the effects of showing/hiding columns

Currently, I'm getting data for a jqgrid using.

347
Lock Datepicker for Bootstrap

Lock Datepicker for Bootstrap

I'm not sure this is possible, but I wanted to post on SOF anyway. .

333