I was looking for some standard function like hex to string but inverse, I want to convert String to Hex, but I only found this function...
// Example of convert hex to String
hex.toString('utf-8')
In NodeJS, use Buffer to convert string to hex.
Buffer.from('hello world', 'utf8').toString('hex');
Simple example about how it works:
const bufferText = Buffer.from('hello world', 'utf8'); // or Buffer.from('hello world')
console.log(bufferText); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
const text = bufferText.toString('hex');
// To get hex
console.log(text); // 68656c6c6f20776f726c64
console.log(bufferText.toString()); // or toString('utf8')
// hello world
//one single line
Buffer.from('hello world').toString('hex')
You can use function like the below:
function stringToHex(str) {
//converting string into buffer
let bufStr = Buffer.from(str, 'utf8');
//with buffer, you can convert it into hex with following code
return bufStr.toString('hex');
}
stringToHex('some string here');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With