Firefox 29 で String.fromCodePoint, String.prototype.codePointAt が実装された

ECMAScript6th における、Unicode をもう少しうまく扱うためのメソッド2つ。従来の String.fromCharCode, String.prototype.charCodeAt の Unicode 対応版と言え、サロゲートペアとなる文字の扱いが変わっている。

今回は「吉野家」の正しい文字として http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=%F0%A0%AE%B7 を使うよ。

var str = "𠮷野家";
var charCodes = [];
for (var i = 0; i < str.length; ++i) {
      charCodes.push(str.charCodeAt(i));
}
console.log("CharCodes(degit): ", charCodes);
// "CharCodes(degit): " [55362, 57271, 37326, 23478]
console.log("CharCodes(hex):", charCodes.map(n => n.toString(16).toUpperCase()));
// "CharCodes(hex):" ["D842", "DFB7", "91CE", "5BB6"]
console.log("fromCharCode:", String.fromCharCode(...charCodes));
// "fromCharCode:" "\uD842\uDFB7\u91CE\u5BB6"
                 
var codePoints = [c.codePointAt(0) for (c of str)];
console.log("CodePoints:", codePoints);
// "CodePoints:" [134071, 37326, 23478]
console.log("fromCodePoint:", String.fromCodePoint(...codePoints));
// "fromCodePoint:" "\uD842\uDFB7\u91CE\u5BB6"

console.log("fromCharCode === fromCodePoint:",
  String.fromCharCode(...charCodes) === String.fromCodePoint(...codePoints));
// "fromCharCode === fromCodePoint:" true

String.prototype.codePointAt は、対象がサロゲートペアな場合にも綺麗にUnicodeのコードポイントを返してくれる。String.fromCodePoint はその逆。

ただし、String.prototype.codePointAt(サロゲートペアの後部のIndex値) とした場合、charCodeAt と同じ値を返してしまう。

var str = "&#134071;野家";
var codePoints = [];
for (var i = 0, len = str.length; i < len; ++i) {
  codePoints.push(str.codePointAt(i);
}

このようなコードを書くと、結果は "CodePoints:" [134071, 57271, 37326, 23478] となってしまい、うまくない感じになる。
Firefox 27(Nightly) における新たな String.prototype["@@iterator"] - hogehoge で紹介した文字列イテレータを使用して、以下のように for-of で書くべき。

var codePoints = [];
for (var char of str) {
  codePoints(char.codePointAt(0));
}
// または

var codePoints = [for (c of str) c.codePointAt(0)];
// Firefox実装では [c.codePointAt(0) for (c of str)];