Kind of a follow up to a question from yesterday. I have a hash that changes values and need to isolate the second half. The code below DOES work, but needs to return false if there isn't a value because I'm using if (val.length){}
later on and it is currently always true. So, to demonstrate:
var hash = window.location.hash,
page = hash.split('=')[0],
val = hash.substr(hash.indexOf('=') + 1);
console.log(hash,page,val);
localhost/#work
console returns: #work, #work, #work
localhost/#work=misery
console returns: #work=misery, #work, misery
I'd like it to return:
localhost/#work
console returns: #work, #work, (no value for val)
localhost/#work=misery
console returns: #work=misery, #work, misery
Thanks for your help!
Just use the same approach you have for page:
var hash = window.location.hash,
values = hash.split("="),
page = values[0],
val = values[1];
console.log(hash,page,val);
localhost/#work
console returns: #work, #work, undefined
localhost/#work=misery
console returns: #work, #work, misery
PS I will suggest to you to add the JavaScript tag and maybe remove the jQuery ones, because it's a question totally unrelated to jQuery.
Just add some logic to check if there is a value
var hash = window.location.hash,
values = hash.split("="),
page = values[0],
val = values[1]?values[1]:'';//you can use if (val.length){} to check if ther is a value
console.log(hash,page,val);
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.