How to convert characters to hex in JavaScript?

Sometimes, we want to convert characters to hex in JavaScript.

In this article, we’ll look at how to convert characters to hex in JavaScript.

How to convert characters to hex in JavaScript?

To convert characters to hex in JavaScript, we can use the string charCodeAt method.

For instance, we write:

const strAsUnicode = (str) => {
  return str.split("").map((s) => {
    return `\u${s.charCodeAt(0).toString(16).padStart(4, '0')}`;
  }).join("");
}

console.log(strAsUnicode('abc'))

to define the strAsUncode function that calls str.split to split the string into an array of characters.

Then we call map on the array with a callback that calls charCodeAt to return the character of code of character s.

Then we convert it to a hex string with toString(16).

And then we call padStart to pad the returned string to 4 characters by prepending 0’s.

Finally, we call join with an empty string to join the returned string array back to a string.

As a result, the console log logs "u0061u0062u0063".

Conclusion

To convert characters to hex in JavaScript, we can use the string charCodeAt method.