How to convert a String to Bytearray Ask Question

How to convert a String to Bytearray Ask Question

How can I convert a string in bytearray using JavaScript. Output should be equivalent of the below C# code.

UnicodeEncoding encoding = new UnicodeEncoding();
byte[] bytes = encoding.GetBytes(AnyString);

As UnicodeEncoding is by default of UTF-16 with Little-Endianness.

Edit: I have a requirement to match the bytearray generated client side with the one generated at server side using the above C# code.

ベストアンサー1

Update 2018 - The easiest way in 2018 should be TextEncoder

let utf8Encode = new TextEncoder();
utf8Encode.encode("abc");
// Uint8Array [ 97, 98, 99 ]

Caveats - The returned element is a Uint8Array, and not all browsers support it.

おすすめ記事