Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get true or false if a number is hexadecimal or not?

Tags:

javascript

I want a method which if given a hexadecimal number (e.g. 0x01) returns true. I tried with a string argument, but I need number type check! For example:

isHex(0x0d) //-> true
isHex(12)   //-> false
like image 991
David Jeong Avatar asked Oct 15 '25 01:10

David Jeong


1 Answers

This is not possible as hexadecimal number literals are just another way of representing the same number (translated during parsing) and there’s no way to differentiate them:

0x10            //=> 16
0x10.toString() //=> '16'
typeof 0x10     //=> 'number'
typeof 16       //=> 'number'

This would only be possible if you passed the literal as a string:

function isHex(num) {
  return Boolean(num.match(/^0x[0-9a-f]+$/i))
}

isHex('0x1a') //=> true
isHex('16')   //=> false
like image 130
Andrew Marshall Avatar answered Oct 17 '25 15:10

Andrew Marshall