Emmanuel Akinfulubi

JavaScriptRegular expressions

Check if a string is hexadecimal in JavaScript

Beginner · 3 min read

Hexadecimal, or hex, is a way of writing numbers with sixteen digits instead of ten. You meet it in color codes like #ff0000, in memory addresses, in file checksums and in IDs like deadbeef. Before a program turns a hex string into a number, it should check the string really is hex.

In this tutorial you will write isHex with a short regular expression, allow the optional 0x prefix, and then convert valid strings to numbers. Along the way you will see why parseInt can't do the checking for you: it returns a confident wrong answer instead of an error. You need to know /.../.test(), ^ and $. Hex itself is explained first.

Hex in one paragraph

Ordinary numbers use the digits 0 to 9. Hex adds six more: a stands for 10, b for 11, up to f for 15. Case doesn't matter, so F is also 15. Each position is worth sixteen times the one to its right, so 1a means one sixteen plus ten:

JavaScript

console.log(0x1a);                 // 26
console.log(Number.parseInt('1a', 16)); // 26

The 0x in front is the usual way to say "this is hex" in code.

A class for hex digits

[0-9a-f] is a character class meaning "one digit from 0 to 9, or one letter from a to f". Adding A-F covers capitals too:

JavaScript

console.log(/^[0-9a-fA-F]+$/.test('ff'));  // true
console.log(/^[0-9a-fA-F]+$/.test('fg'));  // false

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

16 Is the value hexadecimal?

easy

Check whether a string is a hexadecimal number, allowing an optional 0x prefix.

Stuck? Three hints, smallest first
  1. 1. Hex digits are [0-9a-f], with the i flag for upper case.
  2. 2. Make the prefix optional: (0[xX])?.
  3. 3. parseInt(s, 16) parses a prefix and stops, so it is not a validity test.

Step 1: hex digits only

+ means "one or more", and the anchors make sure nothing else is in the string:

JavaScript

const HEX_DIGITS = /^[0-9a-fA-F]+$/;
console.log(HEX_DIGITS.test('deadbeef')); // true
console.log(HEX_DIGITS.test('123'));      // true: plain digits are hex too
console.log(HEX_DIGITS.test('0x1A'));     // false: the x is not a hex digit

Step 2: allow the 0x prefix

Put 0[xX] in a group and make the whole group optional with ?:

Step 2

const HEX = /^(0[xX])?[0-9a-fA-F]+$/;
const isHex = (value) => typeof value === 'string' && HEX.test(value);
console.log(isHex('0x1A')); // true
console.log(isHex('0X1a')); // true
console.log(isHex('1A'));   // true
console.log(isHex('0x'));   // false: a prefix with no digits
console.log(isHex('-1A'));  // false
console.log(isHex('1A '));  // false: trailing space

0x alone fails because + still needs at least one digit after the prefix.

Step 3: why parseInt is not a check

It's tempting to skip the pattern and just try converting. Look at what parseInt does with a bad character:

JavaScript

console.log(Number.parseInt('1G', 16)); // 1
console.log(Number.parseInt('zz', 16)); // NaN

parseInt reads digits from the front until it meets one it doesn't know, then stops and returns what it has. '1G' gives 1: no error, just a wrong answer that looks right. It only gives NaN when it can't read a single digit at the start. This catches people in every base, not only hex.

Step 4: check first, then convert

So test the string first, and only convert if it passes. parseInt with base 16 doesn't need the prefix, so remove it with a small replace:

Step 4

const HEX = /^(0[xX])?[0-9a-fA-F]+$/;
const isHex = (value) => typeof value === 'string' && HEX.test(value);
const hexToNumber = (value) => (isHex(value) ? Number.parseInt(value.replace(/^0[xX]/, ''), 16) : null);
console.log(hexToNumber('1A'));       // 26
console.log(hexToNumber('0x1A'));     // 26
console.log(hexToNumber('ff'));       // 255
console.log(hexToNumber('deadbeef')); // 3735928559
console.log(hexToNumber('0x1G'));     // null

A bad string now gives null, which the caller can check, instead of a quiet wrong number.

Step 5: what Number does

Number is stricter than parseInt, but it only understands hex with the prefix:

JavaScript

console.log(Number('0x1A')); // 26
console.log(Number('1A'));   // NaN

That is why the answer uses parseInt(…, 16) after the check: it works with or without the prefix once the string is known to be clean.

The full solution

The panel runs a list of strings through isHex and hexToNumber, then prints the parseInt and Number surprises side by side. Press Run and look at the '1G' line.

The answer

const HEX = /^(0[xX])?[0-9a-fA-F]+$/;
const isHex = (value) => typeof value === 'string' && HEX.test(value);

// Converting, once you know it is valid.
const hexToNumber = (value) => (isHex(value) ? Number.parseInt(value.replace(/^0[xX]/, ''), 16) : null);

const cases = ['1A', '0x1A', '0X1a', 'ff', 'FF', 'deadbeef', '0', '123',
  'g1', '0x', '1A ', '', '-1A', '0x1G'];

for (const h of cases) {
  console.log(JSON.stringify(h).padEnd(12), 'hex:', String(isHex(h)).padEnd(6), 'value:', hexToNumber(h));
}
console.log('--- why parseInt is not a validity test ---');
console.log("parseInt('1G', 16)   =", Number.parseInt('1G', 16), '<- stopped at the G and returned 1');
console.log("parseInt('zz', 16)   =", Number.parseInt('zz', 16), '<- NaN, at least');
console.log("Number('0x1A')       =", Number('0x1A'), '<- understands the prefix');
console.log("Number('1A')         =", Number('1A'), '<- NaN without it');

Output


      
23 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 23 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

23 checks

test('two hex digits pass', isHex('1A'), true);
test('with the 0x prefix', isHex('0x1A'), true);
test('an upper-case prefix too', isHex('0X1a'), true);
test('lower-case digits', isHex('ff'), true);
test('upper-case digits', isHex('FF'), true);
test('a longer value', isHex('deadbeef'), true);
test('a single zero', isHex('0'), true);
test('decimal digits are valid hex', isHex('123'), true);
test('g is not a hex digit', isHex('g1'), false);
test('the prefix alone is not a number', isHex('0x'), false);
test('a trailing space is refused', isHex('1A '), false);
test('an empty string is refused', isHex(''), false);
test('a minus sign is refused', isHex('-1A'), false);
test('one bad digit spoils it', isHex('0x1G'), false);
test('converting gives the right number', hexToNumber('1A'), 26);
test('the prefix does not change the value', hexToNumber('0x1A'), 26);
test('ff is 255', hexToNumber('ff'), 255);
test('deadbeef is a real number', hexToNumber('deadbeef'), 3735928559);
test('an invalid value converts to null', hexToNumber('0x1G'), null);
test('whereas parseInt would return a partial answer', Number.parseInt('1G', 16), 1);
test('which is why the check comes first', isHex('1G'), false);
test('Number understands the 0x prefix', Number('0x1A'), 26);
test('but not a bare hex string', Number.isNaN(Number('1A')), true);

The pattern is easy. The point is the last few assertions: parseInt('1G', 16) returns 1. It reads valid digits from the front, stops at the first one it does not recognise, and reports what it managed — no error, no NaN, just a wrong answer that looks like a right one. This is the single most common source of parseInt bugs, and it applies in every base.

So validate first, then convert. And note the asymmetry in Number: Number('0x1A') is 26 because it understands the prefix, while Number('1A') is NaN. If you want to read hex without a prefix, parseInt(s, 16) is the right call — after you have checked the string.

Common mistakes

  • Using parseInt as a validity test. It returns a partial number for strings like '1G'. Check with the pattern first.
  • Forgetting capitals. [0-9a-f] alone refuses FF. Add A-F or use the i flag.
  • Leaving out the anchors. Without ^ and $, any string containing one hex digit passes, like 'hello' (it has an e).

Try it yourself

  1. Rewrite HEX with the i flag so the class is just [0-9a-f].
  2. Write numberToHex(n) with n.toString(16) and check numberToHex(255) is 'ff'.
  3. Write isByte(value) that accepts exactly two hex digits, like '0a' or 'FF'.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.