JS Reference
Service Workers
ESModule Tips
NodeJS Tips
Javascript Tips

Regular expression - Hex check

Check if the string is a hex number

Hexadecimal number verification using Regular Expression

Find if the string is a Hex number

Info

To Check if a string is a number in Hex format, the following checks are made. It may contain only the following characters

  • It can start with 0x or not
  • is a numerical digit from 0 to 9
  • is a string character from a to f
  • is a string character from A to F

Sample Code

script.js
Copy
function isHex(str) {
    // Regex to match one or more hex characters from start (^) to end ($) of the string
    const regexp = /^(0x)?[0-9a-fA-F]+$/;
    return regexp.test(str);
}

isHex('0x1f003');   // output: true
isHex('1fzzz');     // output: false