LoginSignup
7
6

More than 5 years have passed since last update.

UTF-8のエンコードとデコード

Last updated at Posted at 2013-02-06

間違いがありましたら、教えていただけると嬉しいです。

function encode(string, encoding) {
    encoding = encoding || "UTF-8";
    if(typeof Buffer === "function") {
        return new Buffer(string, encoding);
    } else {
        var bytes = [];
        var cs = encodeURI(string).match(/(?:%[0-9A-F]{2})|./g);
        for(var i = 0, len = cs.length; i < len; i++) {
            if(cs[i].length === 3) {
                bytes.push(parseInt(cs[i].slice(1), 16));
            } else {
                bytes.push(cs[i].charCodeAt(0));
            }
        }
        return bytes;
    }
}

function decode(bytes, encoding) {
    encoding = encoding || "UTF-8";
    if(typeof Buffer === "function") {
        return bytes.toString(encoding);
    } else {
        var encoded = "";
        for(var i = 0, len = bytes.length; i < len; i++) {
            encoded += "%" + bytes[i].toString(16);
        }
        return decodeURIComponent(encoded);
    }
}
7
6
0

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
7
6