简体   繁体   中英

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

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?

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);
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM