1

I want to run a script that extracts an integer from the URL hash (#), or zero if no integer is found.

The URLs could be any of these formats:

  1. www.example.com/book/#page-cover
  2. www.example.com/book/#page-1
  3. www.example.com/book/#page-12
  4. www.example.com/book/#page-123

The above examples would return:

  1. 0
  2. 1
  3. 12
  4. 123

I'm running jQuery and looking for the cleanest way of doing this in either pure Javascript or jQuery.

Thanks in advance.

0

2 Answers 2

4

You could do it in one line:

var integer = window.location.hash.match(/\d+/) | 0;
  • This will match the first one or more digits in the hash.
  • then bitwise OR the result with 0. Javascript bit operations are on 32-bit signed integer (except >>>)
  • return the result of the match as an integer, or if match is undefined, return zero
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice operations there, although there's no match method on location. Try location.href or location.hash.
2

To get the first integer (not a decimal) in the hash, you could use regex:

var match = location.hash.match(/\d+/);
if(match)
  var n = parseInt(match[0], 10);
else
  var n = 0;

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.