TheAlgorithms/JavaScript · error · Error
Invalid hex string.
Error message
Invalid hex string.
What it means
Thrown by hexToInt (used by hexToDecimal) when hexNum does not match /^[0-9A-F]+$/, i.e. it must be non-empty and contain ONLY uppercase A-F and digits. This is stricter than HexToBinary: lowercase hex, a '0x' prefix, empty string, or any non-hex char all fail. Plain Error (content validation, not type).
Source
Thrown at Conversions/HexToDecimal.js:3
function hexToInt(hexNum) {
if (!/^[0-9A-F]+$/.test(hexNum)) {
throw new Error('Invalid hex string.')
}
const numArr = hexNum.split('') // converts number to array
return numArr.map((item, index) => {
switch (item) {
case 'A':
return 10
case 'B':
return 11
case 'C':
return 12
case 'D':
return 13
case 'E':
return 14
case 'F':
return 15
default:
return parseInt(item)View on GitHub (pinned to 5c39e87a9a)
Solutions
- Uppercase and strip prefixes: const clean = hex.toUpperCase().replace(/^0x/, '').
- Validate with /^[0-9A-F]+$/ before calling.
- Handle empty input upstream instead of forwarding '' to the converter.
Example fix
// before
hexToDecimal('ff')
// after
hexToDecimal('ff'.toUpperCase()) Defensive patterns
Strategy: validation
Validate before calling
const clean = String(hexNum).replace(/^0x/i, '').toUpperCase()
if (!/^[0-9A-F]+$/.test(clean)) {
throw new Error('Invalid hex string')
}
return hexToDecimal(clean) Type guard
const isValidUpperHex = (s) => typeof s === 'string' && /^[0-9A-F]+$/.test(s)
Try / catch
try {
hexToDecimal(hexNum)
} catch (e) {
if (/Invalid hex string/.test(e.message)) {
return hexToDecimal(String(hexNum).replace(/^0x/i, '').toUpperCase())
}
throw e
} Prevention
- Uppercase hex input before calling — the regex only allows A-F.
- Strip '0x' prefixes at the boundary.
- Reject empty strings upstream rather than forwarding them.
When it happens
Trigger: Calling hexToDecimal('ff') (lowercase rejected), hexToDecimal('0xFF') (prefix + lowercase), hexToDecimal('') (empty fails the + quantifier), or hexToDecimal('GG').
Common situations: Lowercase hex from CSS colors (#ffffff) or JSON; values prefixed with '0x' from language literals; empty string from a missing field; lowercase output of another function fed in here.
Related errors
- Argument is not a valid HEX code!
- Duplicate characters in character set are not allowed
- Not a valid character: ${digit}
- Argument is not a string type
- Invalid units
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/f0d24b6da012b429.
Report an issue: GitHub.