convert string to utf8 js in javascript

To convert a string to utf-8 encoding in javascript, you can use the TextEncoder API. Here’s an example:

index.tsx
const encoder = new TextEncoder();
const str = 'Hello, world!';

// Convert string to utf8 buffer
const utf8Buffer = encoder.encode(str);

// Convert utf8 buffer to string
const decoder = new TextDecoder('utf-8');
const utf8String = decoder.decode(utf8Buffer);

console.log(utf8String);  // Hello, world!
305 chars
12 lines

In the above code, we first create a new TextEncoder instance which we’ll use to encode the string. We then use the .encode() method of the TextEncoder to convert the string to a Uint8Array array of bytes in utf-8 encoding.

To convert the utf-8 buffer back to a string, we create a new TextDecoder instance and use the .decode() method to get the utf-8 encoded string.

Note: The TextEncoder and TextDecoder APIs are not supported by some older browsers. So make sure to check browser compatibility before using these APIs in your code.

gistlibby LogSnag