0

Using window.location.hash I get this:

http://example.com         --> ''
http://example.com#        --> ''
http://example.com#ahihah  --> '#ahihah'

However, I need to distinguish between these two cases:

http://example.com         --> ''
http://example.com#        --> '#'
http://example.com#ahihah  --> '#ahihah'

So when there is no hash in the url (first case) it's ok to have an empty string but I want to have the value '#' if there is the hash sign. Is this possible in JavaScript?


I already tried with this.

var hash = window.location.hash;
var href = window.location.href;
if (hash !== '') {
  return link.hash;
}
if (href.slice(-1) === '#') {
  return '#';
}
return '';

But looks like an error-prone method. Could be that a query string in the url ends with # and the function will fall into the second if returning '#' instead of ''?

6
  • 1
    A querystring can't end with #, that would mean there's a location hash after the querystring ? Commented Dec 29, 2015 at 17:14
  • Why do you need to know this anyway, it seems like an X/Y problem ? Commented Dec 29, 2015 at 17:14
  • @adeneo I just added what I tried. I could remove it and ask directly for the problem. I'm looking for a good and robust solution and I'm not sure about mine. Commented Dec 29, 2015 at 17:17
  • And again, what's the use case? Generally it shouldn't matter if the URL ends with an empty hash or doesn't have a hash at all, it's the same thing? Commented Dec 29, 2015 at 17:27
  • @adeneo I get an url and I need to do something different if there is an empty hash or if there isn't any hash. Also browsers behave different in two cases: if I'm to http://example.com and I go to http://example.com (e.g. clicking a link) the page will be reloaded while if I go to http://example.com# the page will scroll on top. I don't know if I answered your question? I just need to do two different things in the first and the second case. Commented Dec 29, 2015 at 17:47

1 Answer 1

1

Your method works fine.

A query string cannot have a # in it (it would need to be encoded as %23, and then href.slice(-1) === 3), since that would be interpreted as the start of a hash, not part of the query string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.