Execute Program

Regular Expressions: Hex Codes

Welcome to the Hex Codes lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Computers internally store text as numbers. As a shorthand, we usually write those numbers out as hexadecimal codes.

  • >
    /\x41/.test('A'); // 'A' is x41
    Result:
    truePass Icon
  • For example, capital letter "A" has the hex code x41. Regular expressions and most programming languages allow this "x" syntax. To match "A" in a regex, we can write \x41.

  • >
    /\x41/.test('an apple');
    Result:
    falsePass Icon
  • >
    /\x41/.test('CATS ARE GOOD');
    Result:
    truePass Icon
  • x42 is "B".

  • >
    /\x42/.test('An apple');
    Result:
    falsePass Icon
  • >
    /\x42/.test('Both apples');
    Result:
    truePass Icon
  • Each digit can be a number, or a letter between "a" and "f". For example, "M" is x4d in hex. (The x isn't a hex digit; it's telling us that this is a hex code.)

  • >
    /\x4d/.test('M');
    Result:
    truePass Icon
  • There's a hex code for each character, even ones that aren't letters. "?" is x3f and "!" is x21.

  • >
    /\x3f/.test('?');
    Result:
    truePass Icon
  • >
    /\x21/.test('!');
    Result:
    truePass Icon
  • We can use hex codes to match symbols that you may not be able to type.

  • The letter "ø" doesn't appear on an US-English keyboard. To match that letter, we can use its hex code \xf8.

  • >
    /\xf8/.test('søt katt');
    Result:
    truePass Icon
  • If we have a keyboard that can type "ø", we can put it directly in a regex.

  • >
    /ø/.test('smørbrød');
    Result:
    truePass Icon
  • Be careful: the syntax \x can only be followed by exactly two digits. Anything after the two digits will be a different part of the regex.

  • >
    /\x41d/.test('A');
    Result:
    falsePass Icon
  • >
    /\x5Ad/.test('Zd'); // "Z" is x5A
    Result:
    truePass Icon
  • If we write an \x with only one digit, it's no longer a character code. Instead, the \x matches literal "x" characters.

  • >
    /\x4/.test('x4'); // This is probably a mistake with \x!
    Result:
    truePass Icon
  • Hexadecimal digits can be any character from 0-9, a-f, or A-F. If we use the wrong characters, the \x will match literal "x" again.

  • >
    /\xfg/.test('xfg');
    Result:
    truePass Icon