title: UTF-8 to UTF-16LE Javascript
body: <p>I need to convert an utf-8 string to utf-16LE in javascript like the iconv() php function.</p>
  
  <p>Ie:</p>
  
  <pre><code>iconv("UTF-8", "UTF-16LE", $string);
  </code></pre>
  
  <p>The output should be like this: </p>
  
  <blockquote>
    <p>49 00 6e 00 64 00 65 00 78 00 </p>
  </blockquote>
  
  <p>I found this func to decode UTF-16LE and it's works fine but i don't know how to do the same to encode.</p>
  
  <pre><code>function decodeUTF16LE( binaryStr ) {
      var cp = [];
      for( var i = 0; i &lt; binaryStr.length; i+=2) {
          cp.push( 
               binaryStr.charCodeAt(i) |
              ( binaryStr.charCodeAt(i+1) &lt;&lt; 8 )
          );
      }
  
      return String.fromCharCode.apply( String, cp );
  }
  </code></pre>
  
  <p>The conclusion is to create a binary file that can be downloaded.</p>
  
  <p>The code:</p>
  
  <pre><code>function download(filename, text) {
      var a = window.document.createElement('a');
  
      var byteArray = new Uint8Array(text.length);
      for (var i = 0; i &lt; text.length; i++) {
          byteArray[i] = text.charCodeAt(i) &amp; 0xff;
      }
      a.href = window.URL.createObjectURL(new Blob([byteArray.buffer], {'type': 'application/type'}));
  
      a.download = filename;
  
      // Append anchor to body.
      document.body.appendChild(a);
      a.click();
  
      // Remove anchor from body
      document.body.removeChild(a);
  }
  </code></pre>