golangの日記

Go言語を中心にプログラミングについてのブログ

JavaScriptで文字コード変換

javascript.png


JavaScriptのライブラリ encoding.js を使った文字コード変換。 (使い方は README_ja.md に日本語ですべて載ってる)


ブラウザで読み込む

<script src="encoding.min.js"></script>


npmでダウンロードする

$ npm i encoding-japanese





Encoding.convert で文字コード変換、Encoding.detect で文字コード判別。

const Encoding = require('encoding-japanese');

const equeal = (a, b) => {
    const {l1, l2} = (a.length, b.length);
    if (l1 != l2) return false;
    for (let i = 0; i < l1 && i < l2; i++)
        if (a[i] !== b[i]) return false;
    return true;
};

// 変換する文字列
let s = 'こんにちは';

// 文字列を配列にしておく
let a = s.split('').map((v) => v.charCodeAt());

// JavaScriptのデフォルトは unicode
console.log(Encoding.detect(a), a);
// UNICODE [ 12371, 12435, 12395, 12385, 12399 ]



let actual, escaped;

// Shift-JIS に変換。
// 第三引数は変換前の文字コード名を指定。省略したら自動判別されるけど指定しておいたほうが速そうなので指定しておく
actual = Encoding.convert(a, 'SJIS', 'UNICODE');

// URL用にエスケープ
escaped = Encoding.urlEncode(actual);

// detect で文字コードを判別できる
console.log(Encoding.detect(actual)); // SJIS

console.log(actual);
// [
//   130, 177, 130, 241,
//   130, 201, 130, 191,
//   130, 205
// ]


// ちゃんとテストは書かれているので必要ないけどテストしてみた
const ExpectShiftJIS = [ 130, 177, 130, 241, 130, 201, 130, 191, 130, 205 ];
const ExpectEscapedShiftJIS = '%82%B1%82%F1%82%C9%82%BF%82%CD';
console.log('ShiftJIS:',
            equeal(ExpectShiftJIS, actual), // true
            ExpectEscapedShiftJIS === escaped); // true



// EUC-JP に変換

actual  = Encoding.convert(a, 'EUCJP', 'UNICODE');
// URL用にエスケープ
escaped = Encoding.urlEncode(actual);

console.log(Encoding.detect(actual)); // EUCJP
console.log(actual);
// [
//   164, 179, 164, 243,
//   164, 203, 164, 193,
//   164, 207
// ]

// テスト
const ExpectEucJP = [ 164, 179, 164, 243, 164, 203, 164, 193, 164, 207 ];
const ExpectEscapedEucJIS = '%A4%B3%A4%F3%A4%CB%A4%C1%A4%CF';
console.log('EucJP:',
            equeal(ExpectEucJP, actual), // true
            ExpectEscapedEucJIS == escaped); // true