Categories
JavaScript Answers

How to convert Unicode string to hex with JavaScript?

Spread the love

Sometimes, we want to convert Unicode string to hex with JavaScript.

In this article, we’ll look at how to convert Unicode string to hex with JavaScript.

How to convert Unicode string to hex with JavaScript?

To convert Unicode string to hex with JavaScript, we can use the decodeURIComponent function.

For instance, we write

const fromHex = (hex) => {
  let str;
  try {
    str = decodeURIComponent(hex.replace(/(..)/g, "%$1"));
  } catch (e) {
    console.log("invalid hex input: " + hex);
  }
  return str;
};

to call decodeURIComponent on the string with the hex string.

Then we return it.

To decode it, we write

const toHex = (str) => {
  let hex;
  try {
    hex = unescape(encodeURIComponent(str))
      .split("")
      .map((v) => {
        return v.charCodeAt(0).toString(16);
      })
      .join("");
  } catch (e) {
    console.log("invalid text input: " + str);
  }
  return hex;
};

to call encodeURIComponent to encode the str string.

Then we call unescape on the encoded string to unescape the URI encoded string.

We then split the string with split and map the characters into hex with map.

Then we call join to join the mapped characters back together.

Conclusion

To convert Unicode string to hex with JavaScript, we can use the decodeURIComponent function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *