1

I am developing a web page that communicates with the server via AJAX. The server is expecting binary data in a specific format. At the moment my JavaScript code can generate the entire data the server is expecting, except for one part which consists of a UTF-8 representation of some string parameter.

In short, what I need is a JavaScript function that gets a string s and returns its UTF-8 representation as a Uint8Array.

This is very easy in Firefox, which has the TextEncoder class:

function utf8(s) {
  return new TextEncoder().encode(s);
}

Unfortunately, Firefox is not the only browser out there ;-) Does anyone know of a way to do this cross-browser?

I could write up my own encoder, but I'd rather use something native if it's possible.

Note: I would gladly welcome a non-cross-browser solution as long as it works on Google Chrome.

7
  • Since you know that the solution to your problem is an UTF-8 encoder, I 'm voting to close this because it asks for a library recommendation. Google can answer it in a second. Commented Jun 8, 2014 at 11:42
  • @Jon - I'm not looking for a library. Also, Google did not answer my question (Google was my first, and second, ... and tenth attempt before coming to SO). Commented Jun 8, 2014 at 11:46
  • Well, it answered the question for me. Commented Jun 8, 2014 at 11:50
  • @Jon - can you point me to a specific link? I checked a few and none of them provides what I want. (Notice I want the UTF-8-encoding in binary, i.e. Uint8Array, not as text.) Commented Jun 8, 2014 at 11:59
  • This is a UTF-8 encoder/decoder. If you don't want the result in a string but rather in an Uint8Array then simply don't put the encoding results into a string with String.fromCharCode but directly write the char code into the array instead. Commented Jun 8, 2014 at 12:09

1 Answer 1

1

There is a polyfill for the Encoding Living Standard API, which TextEncoder is part of.

TextEncoder is shipping in Chrome 38. See Encoding API entry from Chromium Dashboard and Chromium Issue 398149: Text Encoding API.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, @Kevin! Not so relevant for me anymore, but I hope someone might find it useful in the future.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.