Francisc
Francisc

Reputation: 80415

Blob URL with UTF-16LE encoding

I have this string %22%00%41%00%22%00%09%00%22%00%42%00%22%00 which is the UTF-16LE equivalent of "A"\t"B". (The \t is a Tab char.)

I am trying to construct a Blob and then a URL for it, but the output isn't decoded to proper entities.

var blob=new Blob([stringHere],{type:'text/csv;charset=UTF-16LE;'});
var blobUrl=URL.createObjectURL(blob);

Is there anyway to tell the Blob the string encoding so that it looks properly when opened in Excel (in this particular case)?

I need UTF-16LE, otherwise using UTF-8 will result in Excel no parsing the .csv file properly.

Thanks.

Upvotes: 2

Views: 4449

Answers (1)

Musa
Musa

Reputation: 97672

It looks like you need a utf-16 le bom in the file, which you can't do with a string in js, so you'll have to use a byte array. See example below

var stringHere = '%ff%fe%22%00%41%00%22%00%09%00%22%00%42%00%22%00';
var byteArray = [];
stringHere.replace(/([0-9a-f]{2})/gi, function(d){
    byteArray.push(parseInt(d, 16));
});
var blob=new Blob([new Uint8Array(byteArray)],{type:'text/csv;charset=UTF-16LE;'});
var blobUrl=URL.createObjectURL(blob);

Upvotes: 2

Related Questions