LoginSignup
2
2

JavaScript で文字列を Shift_JIS に変換

Posted at

Encoding API

TextEncoder で変換すれば… utf-8 のみ …だと?…((((;゚Д゚)))))))

TextEncoder: encoding プロパティ

持つことができる値は utf-8 のみです。

TextDecoder で逆変換はできるのに… (´・ω・`)

TextDecoder: encoding プロパティ

日本語の古いマルチバイトエンコーディング: euc-jp, iso-2022-jp, shift-jis

Decoder があれば Encoder もできる!

const table = { '\u00a5': 0x5c, '\u203e': 0x7e, '\u301c': 0x8160 };

const decoder = new TextDecoder('shift-jis');

for (let i = 0x81; i <= 0xfc; i++) {
    if (i <= 0x84 || i >= 0x87 && i <= 0x9f || i >= 0xe0 && i <= 0xea || i >= 0xed && i <= 0xee || i >= 0xfa) {
        for (let j = 0x40; j <= 0xfc; j++) {
            const c = decoder.decode(new Uint8Array([i, j]));
            if (c.length === 1 && c !== '\ufffd' && !table[c]) {
                table[c] = i << 8 | j;
            }
        }
    }
}

function encode(content) {
    let buffer = [];
    for (let i = 0; i < content.length; i++) {
        const c = content.codePointAt(i);
        if (c > 0xffff) {
            i++;
        }
        if (c < 0x80) {
            buffer.push(c);
        }
        else if (c >= 0xff61 && c <= 0xff9f) {
            buffer.push(c - 0xfec0);
        }
        else {
            const d = table[String.fromCodePoint(c)] || 0x3f;
            if (d > 0xff) {
                buffer.push(d >> 8 & 0xff, d & 0xff);
            }
            else {
                buffer.push(d);
            }
        }
    }
    return Uint8Array.from(buffer);
};

いくぞ! 9, 3, 2, ダァーッ!

const shiftjis = encode('JavaScript で文字列を Shift_JIS に変換');

console.log(shiftjis);
// Uint8Array(38) [74, 97, 118, 97, 83, 99, 114, 105, 112, 116, 32, 130, 197, 149, 182, 142, 154, 151, 241, 130, 240, 32, 83, 104, 105, 102, 116, 95, 74, 73, 83, 32, 130, 201, 149, 207, 138, 183, buffer: ArrayBuffer(38), byteLength: 38, byteOffset: 0, length: 38, Symbol(Symbol.toStringTag): 'Uint8Array']

console.log(decoder.decode(shiftjis));
// JavaScript で文字列を Shift_JIS に変換

ではまた!

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2