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
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
Share
Improve this question
edited Dec 26, 2016 at 16:16
Andrew Marshall
96.9k20 gold badges227 silver badges217 bronze badges
asked Dec 26, 2016 at 16:08
David JeongDavid Jeong
1191 silver badge9 bronze badges
5
|
6 Answers
Reset to default 12This 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
JavaScript cannot tell you how a value of any type was achieved. Much like you can't reach from 12
back to 6+6
or 3*4
. 0x0d
and 12
are the exact same value.
The option to type numbers in hexadecimal or octal notation besides decimal notation is merely a syntax affordance. You're not creating any sort of different numerical value. 0x0D
(hexadecimal) is exactly the same numerical value as 13
(decimal) is exactly the same as 015
(octal). Merely their notation differs by their radix. It is sometimes convenient to work with numbers in different radices, it doesn't change the actual number.
Long story short: you can't tell the difference.
You can't. Your number literal is parsed to a number value before being passed to the function. The function only receives the a 64-bit number value which represents e.g. 13, but it can't know whether you wrote 13
, 13.0
, 0b1101
, 0xd
or 0o15
, or even more complex expressions like 26 / 2
or 10+3
.
This kind of information is not exposed in JavaScript. The only way you might manage to do it would be getting the source code of your script, and using your own JS parser.
Alternatively, consider passing a string instead.
^([0-9A-Fa-f])+$
is the unique pattern that is working for me
I don't know if this helps but I use logic like below to block dodgy domain scripts from loading in a browser, such as this URL:
https://0e29fa5ee4.09b074f4cf.com/165575ce5432f25ac96b16e917b1750c.js
The logic used once components have been extracted from the URL is basically...
var S='0e29fa5ee4';
var IsHex=parseInt(S,16).toString(16)===S.toLowerCase();
NB: Of course you may also lose some valid domains such as "abba" so a little more logic may be needed.
0x...
is merely different syntax to express a number. The result is still a pure numeric value, no different than when you type it in as decimal number. – deceze ♦ Commented Dec 26, 2016 at 16:10