开发者

How to return integer from URL hash using Javascript

开发者 https://www.devze.com 2023-04-05 12:26 出处:网络
I want to run a script that extracts an integer from the URL hash (#), or zero if no integer is found.

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 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消