Ⅰ. はじめに
タイトルの通り「JavaScriptでテキストファイルの文字コードを自動判定してUNICODEに変換する方法」です。
Ⅱ. 手順
1. サンプルプログラムを書く
<html> <body> <input type="file" id="file001" accept="text/plain"> <script> const file001 = document.getElementById('file001') file001.addEventListener('change', onFileChanged) function onFileChanged (event) { const file = file001.files[0] const reader = new FileReader() reader.onload = async (e) => { // ファイルの文字コードを自動判定してUNICODEに変換する let text = e.target.result.toString() let bytes = Encoding.stringToCode(text) const encoding = Encoding.detect(bytes) bytes = Encoding.convert(bytes, { to: 'UNICODE', from: encoding }) text = Encoding.codeToString(bytes) console.log(text) } reader.readAsBinaryString(file) } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/encoding-japanese/2.0.0/encoding.min.js"></script> </body> </html>
実行結果
省略