-2

For examle I need to check string '69S0' - is it correct a 16x based number. I do not need to parse just check true or false. So, what is an effcient way to do this?

A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48
  • I mean, if you only need to check within a very limited range (say, < 10000), you could build a `Set` containing the string version in standard decimal form of every multiple of 16, and then when you needed to check the string you could see if it's in the set, but... – T.J. Crowder Aug 11 '21 at 09:29
  • @T.J.Crowder actually parseInt('0cb41',16) return nuber 69 (but its not). So parsing can't answer is it correct number. – A1exandr Belan Aug 11 '21 at 09:32
  • 1
    Read the [answer I pointed you to](https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875). :-) But just for what it's worth, `parseInt('0cb41',16)` returns 52033 (decimal), not 69. – T.J. Crowder Aug 11 '21 at 09:34
  • `is16 = s => parseInt(s, 16).toString(16) === (s.toString().replace(/^0+/, '').toLowerCase() || '0');` – Bravo Aug 11 '21 at 09:38
  • @T.J.Crowder Sorry, not '0cb41' my mistake. But parseInt('69S0',16) return 69. – A1exandr Belan Aug 11 '21 at 09:41
  • @FFire - `parseInt('69S0',16)` returns 105, not 69, but yes `parseInt` will just stop when it hits an invalid digit (`S` in that case). The answer linked above talks about that and offers alternatives. – T.J. Crowder Aug 11 '21 at 09:43
  • 1
    Ah, "16x based number" => "base 16 number"! (E.g., hexadecimal.) I'm sorry, I thought you meant "multiple of 16". – T.J. Crowder Aug 11 '21 at 09:44

1 Answers1

3

You can check to see if the string contains any invalid digits. The valid digits are 0-9 and ABCDEF, so:

if (/^[0-9a-f]+$/i.test(theString)) {
    // yes, valid hex
} else {
    // not valid hex
}

Alternatively, you could parse the string using the Number function (note this logic is the other way around):

if (isNaN(Number("0x" + theString)) {
    // not valid hex
} else {
    // yes, valid hex
}

That works because Number accepts certain number base prefixes (0x = hex, 0b = binary, and 0o = octal), and returns NaN if the entire string isn't a valid number using that number base. (And unlike Number(""), which returns 0, Number("0x") returns NaN, so it'll work if theString is blank, too.)


In comments you mentioned that you couldn't rely on parseInt, and you're right: Instead of throwing an error or returning NaN if there's an invalid digit, parseInt just stops parsing and returns what it found at the beginning of the string. (Details in this answer.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875