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:
- www.example.com/book/#page-cover
- www.example.com/book/#page-1
- www.example.com/book/#page-12
- www.example.com/book/#page-123
The above examples would return:
- 0
- 1
- 12
- 123
I'm running jQuery and looking for t开发者_开发知识库he cleanest way of doing this in either pure Javascript or jQuery.
Thanks in advance.
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
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;
精彩评论