JSFiddle - React, Tailwind, and code Playground
JavaScript
var BlobBuilder =
window.WebKitBlobBuilder ||
window.MSBlobBuilder ||
window.MozBlobBuilder ||
window.BlobBuilder;
/**
any encoding -> utf-8
@param {Array|Uint8Array|ArrayBuffer|string} s source
@param {string} encoding source encoding
@param {functon(ArrayBuffer)} callback
*/
var toUTF8 = function(s, encoding, callback) {
if(Array.isArray(s) || s.constructor === Uint8Array) {
s = new Uint8Array(s).buffer;
}
var bb = new BlobBuilder,
fr = new FileReader;
function toArrayBuffer(fr, bb) {
fr.onloadend = function() {
callback(this.result);
};
fr.readAsArrayBuffer(bb.getBlob());
}
bb.append(s);
if(typeof from === 'string') {
toArrayBuffer(fr, bb);
} else {
fr.onloadend = function() {
var bb = new BlobBuilder,
fr = new FileReader;
bb.append(this.result);
toArrayBuffer(fr, bb);
};
fr.readAsText(bb.getBlob(), encoding);
}
};
//test
function t(label) {
var correct = [0xe3, 0x81, 0x93, 0xe3, 0x82, 0x93, 0xe3, 0x81, 0xab, 0xe3, 0x81, 0xa1, 0xe3, 0x81, 0xaf];
return function(arg) {
var arr = new Uint8Array(arg);
for(var i = 0, n = correct.length; i < n; ++i) {
if(arr[i] !== correct[i]) {
document.write(false);
break;
}
}
i === n && document.write(label + " ok<br>");
};
}
toUTF8("こんにちは", null, t('unicode')); //unicode
toUTF8([0x82, 0xb1, 0x82, 0xf1, 0x82, 0xc9, 0x82, 0xbf, 0x82, 0xcd], 'Shift_JIS', t('sjis'));
toUTF8([0xa4, 0xb3, 0xa4, 0xf3, 0xa4, 0xcb, 0xa4, 0xc1, 0xa4, 0xcf], 'EUC-JP', t('eucjp'));