I need to convert an utf-8 string to utf-16LE in javascript like the iconv() php function.
Ie:
iconv("UTF-8", "UTF-16LE", $string);
The output should be like this:
49 00 6e 00 64 00 65 00 78 00
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.
function decodeUTF16LE( binaryStr ) {
var cp = [];
for( var i = 0; i < binaryStr.length; i+=2) {
cp.push(
binaryStr.charCodeAt(i) |
( binaryStr.charCodeAt(i+1) << 8 )
);
}
return String.fromCharCode.apply( String, cp );
}
The conclusion is to create a binary file that can be downloaded.
The code:
function download(filename, text) {
var a = window.document.createElement('a');
var byteArray = new Uint8Array(text.length);
for (var i = 0; i < text.length; i++) {
byteArray[i] = text.charCodeAt(i) & 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);
}
Thanks a lot Bergi, this works perfectly combining to standard utf8 to utf16 encode function:
This should do it:
It's the inverse of your
decodeUTF16LE
function. Notice that neither works with code points outside of the BMP.