JavaScript: Convert String to Hex and Vice Versa

Updated: June 17, 2023 By: Khue Post a comment

A hex value (or a hexadecimal value) is a number that is represented in base 16, using digits from 0 to 9 and letters from A to F. A hex representation of a string is a way of encoding each character of the string as a hex value, usually by using the ASCII code of the character. For example, the string can be represented as 736c696e6761636164656d792e636f6d in hex.

This succinct, practical article will show you how to convert a string to a hex representation and vice versa in modern JavaScript.

Converting a String to a Hex Representation

The main idea here is to use the charCodeAt() method to get the Unicode value of each character in the string and then utilize the toString() method with a radix of 16 to convert the Unicode values to hexadecimal representation.

The steps:

  1. Iterate over each character in the string with a for loop.
  2. Use charCodeAt() to get the Unicode value of the character.
  3. Convert the Unicode value to hexadecimal using toString(16).
  4. Concatenate the hexadecimal values to form the hexadecimal string representation.

Code example:

// define a function that converts a string to hex
const stringToHex = (str) => {
  let hex = '';
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    const hexValue = charCode.toString(16);

    // Pad with zeros to ensure two-digit representation
    hex += hexValue.padStart(2, '0');
  return hex;

// Example usage
console.log(stringToHex("Welcome to Sling Academy!"))



Converting a Hex Representation to a String

To turn a hex representation into a string, you can use the parseInt() function to convert the hex value to decimal and then call String.fromCharCode() to convert the decimal value to the corresponding character. The steps below will clarify what I mean:

  1. Split the input hex string into pairs of hex digits.
  2. Iterate over each pair and convert it to decimal using parseInt() with a radix of 16.
  3. Use String.fromCharCode() to convert the decimal value to the corresponding character.
  4. Concatenate the characters to form the resulting string.

Code example:

// Define a function to convert hex to string
const hexToString = (hex) => {
  let str = '';
  for (let i = 0; i < hex.length; i += 2) {
    const hexValue = hex.substr(i, 2);
    const decimalValue = parseInt(hexValue, 16);
    str += String.fromCharCode(decimalValue);
  return str;

// Example usage



That’s it. The tutorial ends here (I don’t want you to get bored with meaningless words). Happy coding & have a nice day!