简体   繁体   中英

Get values from hash in URL using jquery

If I re-rite the URL using :

var id = 150
window.location.hash = "id="+id;

how to get the value of id using jQuery ?

No jQuery needed..

var id = /^#?id=(.+)/.exec(location.hash);
id = id ? id[1] : '';
// OR
var id = location.hash.substr(4);  // (when hash can only be #id=..)
                                   // This also selects 123 in #no=123 (!)  

+1 for Rob W 's answer not to use jQuery for this. But there're two things, i'd like to point out.

1.) Executing a regular expression, plus using a tertiary operator is "overload" , too. ;-)
2.) You should consider that some browers return the hash symbol, and some don't!

To avoid to truncate the actual value part, I'd say it's safer to use replace() , instead of substr() :

var id = location.hash.replace('id=', '').replace('#', '');

UPDATE:
I think split() is an even better solution:

var id = location.hash.split('id=')[1];

Just one (native) function call, which also "checks" if the request URL actually contains a hash that contains the string "id=idString" .

If it does, the value of var id is "idString" . If not , value of var id is undefined .

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