Working with hexadecimal (hex) data is a common task in programmingâespecially when dealing with low-level operations, cryptography, networking, or handling data from hardware devices. JavaScript provides several robust ways to convert hexadecimal values into human-readable strings. Whether youâre working in the browser or Node.js, understanding these methods will help you handle hex conversion efficiently.
In this guide, weâll explore multiple approaches to convert hex to string in JavaScript, from simple ASCII conversions to handling complex UTFâ8 characters. Weâll also cover common pitfalls and show you how to test your conversions quickly with an online tool.
What Is Hexadecimal and Why Convert It to a String?
Hexadecimal (baseâ16) represents numbers using digits 0â9 and letters AâF. Each hex digit corresponds to 4 bits, so two hex digits make up one byte (8 bits). When data is transmitted or stored as hex (e.g., in APIs, file contents, or color codes), it often needs to be converted back to plain text.
Common scenarios include:
- Decoding hexâencoded API responses.
- Reading data from embedded systems or network packets.
- Converting color codes (like
#FF5733) into readable names. - Handling cryptographic hashes or binary data.
JavaScriptâs builtâin functions make this conversion straightforward, but you must consider character encoding and data formatting.
Prerequisites
You only need a basic understanding of JavaScript and a modern browser or Node.js environment. All examples are pure JavaScript and can be tested in the console or any online editor.
Method 1: Manual Conversion with parseInt() and String.fromCharCode()
The most fundamental approach is to split the hex string into twoâcharacter chunks, convert each chunk to a decimal byte value, and then map that byte to a character using String.fromCharCode().
Example: Convert "48656c6c6f" (which stands for âHelloâ)
function hexToString(hex) {
let str = '';
for (let i = 0; i < hex.length; i += 2) {
const byte = hex.substr(i, 2);
const charCode = parseInt(byte, 16);
str += String.fromCharCode(charCode);
}
return str;
}
const hex = "48656c6c6f";
console.log(hexToString(hex)); // Output: Hello How it works:
hex.substr(i, 2)extracts two characters at a time.parseInt(byte, 16)converts the hex pair to a decimal number (0â255).String.fromCharCode()turns that number into a character.
Note: This method assumes the hex string represents ASCII or ISOâ8859â1 characters (one byte per character). It works perfectly for English letters and common symbols.
Method 2: Handling Separated Hex Pairs
Often hex data comes with delimiters like spaces, commas, or 0x prefixes. For example: "48 65 6c 6c 6f" or "0x48,0x65,0x6c,0x6c,0x6f". You need to clean the string first.
Example: Parse SpaceâSeparated Hex
function hexStringWithSpacesToStr(hexWithSpaces) {
const hexArray = hexWithSpaces.split(' ');
let result = '';
for (const hexPair of hexArray) {
result += String.fromCharCode(parseInt(hexPair, 16));
}
return result;
}
console.log(hexStringWithSpacesToStr("48 65 6c 6c 6f")); // Hello For hex values prefixed with 0x, you can remove the prefix before parsing:
function cleanHex(hex) {
return hex.replace(/0x/g, ''); // Remove all occurrences of "0x"
} Method 3: Modern ES6 Approach with map() and reduce()
You can write more concise and functional code using Array.from(), match(), and reduce().
Using match() to Extract Hex Pairs
const hex = "48656c6c6f";
const hexPairs = hex.match(/.{1,2}/g); // ['48', '65', '6c', '6c', '6f']
const result = hexPairs.map(pair => String.fromCharCode(parseInt(pair, 16))).join('');
console.log(result); // Hello Or in a single line:
const hexToString = (hex) => hex.match(/.{1,2}/g).map(b => String.fromCharCode(parseInt(b, 16))).join(''); This method is compact and elegant, making it a favorite among modern JavaScript developers.
Method 4: Handling UTFâ8 MultiâByte Characters
The previous methods fail when the hex string contains characters outside the ASCII range, such as emojis or accented letters (e.g., "c3a9" for âĂŠâ). Thatâs because UTFâ8 uses one to four bytes per character. You need to interpret the hex as a UTFâ8 byte sequence.
Using TextDecoder (Browser and Node.js)
The TextDecoder API is designed to decode byte arrays into strings using a specific encoding (UTFâ8 by default).
function hexToUtf8String(hex) {
// Convert hex string to a Uint8Array of bytes
const bytes = new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
return new TextDecoder('utf-8').decode(bytes);
}
console.log(hexToUtf8String("c3a9")); // ĂŠ
console.log(hexToUtf8String("e4bda0e5a5bd")); // ä˝ ĺĽ˝ (Chinese)
console.log(hexToUtf8String("f09f918d")); // đ (thumbs up emoji) Why this works:
TextDecoder correctly reads variableâlength UTFâ8 sequences, so you donât have to worry about manual byteâtoâcharacter mapping.
Important: In Node.js,
TextDecoderis available globally (since v8.3.0). For older environments, you can use thebuffermodule (see next section).
Method 5: Node.js Buffer Method
If you are working in a Node.js environment, the Buffer class provides a simple way to convert hex to string.
function hexToStrNode(hex) {
return Buffer.from(hex, 'hex').toString('utf-8');
}
console.log(hexToStrNode("48656c6c6f")); // Hello
console.log(hexToStrNode("e4bda0e5a5bd")); // ä˝ ĺĽ˝ Buffer.from(hex, 'hex') parses the hex string directly, and .toString('utf-8') decodes it. You can also specify other encodings like 'ascii' or 'latin1' if needed.
Common Pitfalls and How to Avoid Them
1. OddâLength Hex Strings
A valid hex string should have an even number of characters (each byte = two hex digits). If the length is odd, you might lose the last character or get incorrect results.
function safeHexToStr(hex) {
if (hex.length % 2 !== 0) {
console.warn('Hex string has odd length â prepending a zero');
hex = '0' + hex;
}
// proceed with conversion...
} 2. Invalid Hex Characters
Characters outside 0-9A-Fa-f will cause parseInt() to return NaN. Always sanitize or validate the input.
const isValidHex = /^[0-9A-Fa-f]+$/.test(hex); 3. Encoding Mismatch
If your hex data comes from a source that uses UTFâ16 or another encoding, using simple ASCII conversion will produce garbled text. Always verify the original encoding.
Try This Hex to String Tool
Testing hex conversions manually can be timeâconsuming, especially when youâre debugging. To speed up your workflow, you can use an online tool that instantly decodes hex data into readable text.
đ Try this hex to string tool â it supports both ASCII and UTFâ8 decoding, allows pasting hex with or without separators, and gives you immediate results. Itâs a great companion while you refine your JavaScript code.
Full Example: A Robust Utility Function
Hereâs a versatile function that combines the best practices: it handles UTFâ8, supports optional delimiters, and works in both browser and Node.js.
function hexToString(hex, options = {}) {
const { delimiter = '', encoding = 'utf-8' } = options;
// Remove any nonâhex characters if a delimiter is provided
let cleanHex = hex;
if (delimiter) {
cleanHex = hex.split(delimiter).join('');
}
// Ensure even length
if (cleanHex.length % 2 !== 0) {
cleanHex = '0' + cleanHex;
}
// Convert hex to byte array
const bytes = new Uint8Array(cleanHex.match(/.{1,2}/g).map(b => parseInt(b, 16)));
// Decode with TextDecoder (browser/Node) or fallback for ASCII
if (typeof TextDecoder !== 'undefined') {
return new TextDecoder(encoding).decode(bytes);
} else {
// Fallback for older environments (ASCII only)
let result = '';
for (let i = 0; i < bytes.length; i++) {
result += String.fromCharCode(bytes[i]);
}
return result;
}
}
// Usage examples
console.log(hexToString("48656c6c6f")); // Hello
console.log(hexToString("48 65 6c 6c 6f", { delimiter: ' ' })); // Hello
console.log(hexToString("e4bda0e5a5bd", { encoding: 'utf-8' })); // ä˝ ĺĽ˝ Conclusion
Converting hexadecimal to a string in JavaScript is straightforward once you understand the dataâs encoding and choose the right method. For simple ASCII, the manual loop or ES6 mapping works perfectly. For international text or emojis, always use TextDecoder or Node.js Buffer.
Remember to handle edge cases like oddâlength strings and invalid characters to make your code robust. And whenever you need a quick sanity check, the online hexâtoâstring tool linked above can save you valuable time.
Now youâre ready to decode hex data with confidence in any JavaScript project!