Convert string into utf-8 encode
In JavaScript, strings are already UTF-8 encoded by default. However, if you need to explicitly handle UTF-8 encoding (e.g., for buffer manipulation), you can use the Buffer class.
function utf8Encode(str) {
// Convert the string to a Buffer to get the UTF-8 bytes
const utf8Buffer = Buffer.from(str, 'utf-8');
// Convert the Buffer back to a string to visualize the bytes
// (for demonstration purposes, showing the hex representation)
const utf8Encoded = utf8Buffer.toString('hex');
return utf8Encoded;
}
// Example usage
const str = "Hello, world!";
const utf8Encoded = utf8Encode(str);
console.log("UTF-8 Encoded (Hex):", utf8Encoded);