4

Only one question: How can I convert string to hex in ethers.js

I need some alternative to web3.utils.utf8ToHex() in ethers.

1
  • What does the string look like? Is it something like "0x123beef"?
    – Linum Labs
    Apr 8, 2021 at 8:48

3 Answers 3

3

I couldn't find such a function in ethers.js (hexlify doesn't accept strings as input), but maybe you'll find this utf8ToHex helper function useful:

function utf8ToHex(str) {
  return '0x' + Array.from(str).map(c =>
    c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) :
    encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
  ).join('');
}

const string = 'test';
const hexString = utf8ToHex(string);
const web3HexString = web3.utils.utf8ToHex(string);
console.log(hexString, web3HexString);
15

Good news! Ethers can natively read strings like "0x123beef" as a datatype it calls a HexString (source)

Once you have a HexString, the docs for the available functions/methods are here.

Update: This answer assumes the goal is to go from a hex value that is encoded as a string, like "0x123beef". If you have an arbitrary string (eg "yo wassup"), you would first need to convert it into utf-8 array, and then make it into a hex:

ethers.utils.hexlify(ethers.utils.toUtf8Bytes("yo wassup"));
// output: 0x796f20776173737570
2
  • The question is how to go from a string like "sif" to a hex string like 0x736966 though. Jul 14, 2021 at 23:07
  • 1
    @JamesMoore We'd assumed the intent was for values like "0x123beef", but have updated the answer to include arbitrary strings too!
    – Linum Labs
    Jul 19, 2021 at 13:35
0

You can use formatBytes32String.

ethers.utils.formatBytes32String("YOUR_STRING")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.