How to check if string is hexadecimal

Hi, how can I do this in javascript to check if the string is valid hexadecimal ?

Thank you in advance.

Use a Regular Expression:

var re = /[0-9A-Fa-f]{6}/g;
var inputString = 'AABBCC';

if(re.test(inputString)) {
    alert('valid hex');
} else {
    alert('invalid');
}

re.lastIndex = 0; // be sure to reset the index after using .text()

Alternative test without needing regexp.

function isHex(h) {
var a = parseInt(h,16);
return (a.toString(16) === h)
}

Except that doesn’t work.

yes it does.

it is your alert() that isn’t working because alert() has no way to convert a boolean to a string to display it. I had the same problem when I tested the code in jsBin when I was making sure it worked just before I posted it. I know the function works because I tested it immediately before posting it just to make sure I hadn’t made any typos.

Simply replace your alert(isHex('AABBCC')); with

if (isHex('AABBCC')) alert('true'); else alert('false');

and you will see that it does work.

Okay I left out one small piece:

function isHex(h) {
var a = parseInt(h,16);
return (a.toString(16) ===h.toLowerCase())
}

Thank you for the reply, what do you mean by your regex {6} ?

Thank you ok I will try this also.

That means exactly six of characters that match the previous pattern

1 Like

Plus, if you go with the regexp, you’ll want the start and end anchors (^ $), otherwise even blah AABBCC blah would test valid.

Normally I favor straightforward solutions rather than clever tricks, but this time I think the parseInt trick has fewer chances for human error to creep in, and that’s the solution I would go with.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.