Polyfill for Utf8toUtf16 for JavaScript

As we know the TextEncoder will drop support utf-16 and other legacy encoding types from Mozilla. Google also confirmed it and Chrome will only remain support utf-16 encoding.

Here is a polyfill implementation for convert utf-8 string to utf-16le

  1. function utf8ToUtf16(s) {
  2. var a = new Uint8Array(s.length * 2),
  3. view = new DataView(a.buffer);
  4. s.split('').forEach(function (c, i) {
  5. //the third parameter equal to true indicate little ending
  6. view.setUint16(i * 2, c.charCodeAt(0), true);
  7. });
  8. return a;
  9. }

 

Reference:
https://bugzilla.mozilla.org/show_bug.cgi?id=1257877
https://www.chromestatus.com/feature/5630760492990464

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>