Vlad
Vlad

Reputation: 2773

Parsing string value to hex in JavaScript

That is quite strange, isn't it? If I recall only 0-9, A, B, C, D, E, F letters represent a hexadecimal value. How come ABCDEFGHAIJ has hexadecimal representation?

Parsing string to hex number in javascript.

Upvotes: 1

Views: 3075

Answers (1)

Arnauld
Arnauld

Reputation: 6110

As mentioned by epascarello in the comments, here is the relevant part of the MDN documentation to explain this behavior:

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Consequently, parseInt("abcdefghij", 16) will actually parse "abcdef" and stop there. Hence the result:

0xABCDEF = 11259375

Knowing this, you may want to use a custom function that will instead return NaN when invoked with a non-hexadecimal string:

function parseTrueHexa(str) {
  return str.match(/^ *[a-f0-9]+ *$/i) ? parseInt(str, 16) : NaN;
}

console.log("parseInt() says:");
console.log(parseInt("aBcD", 16));
console.log(parseInt("abcdz", 16));

console.log("parseTrueHexa() says:");
console.log(parseTrueHexa("aBcD"));
console.log(parseTrueHexa("abcdz"));

Upvotes: 1

Related Questions