Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

String.prototype.codePointAt()

codePointAt() メソッドは、Unicode ポイント値である負でない整数を返します。

構文

str.codePointAt(pos)

引数

pos
コードポイント値を返す文字列内の要素の位置

戻り値

与えられたインデックスにある文字のコードユニット値を示す数値。pos に要素がない場合、 undefined

説明

指定した位置に要素がない場合、undefinedが返されます。UTF-16サロゲートペアがposから始まらないなら、posのコードユニットが返されます。

例: codePointAt()を使う

'ABC'.codePointAt(1);          // 66
'\uD800\uDC00'.codePointAt(0); // 65536

'XYZ'.codePointAt(42); // undefined

互換性

次のコードでは、ネイティブにサポートしていないブラウザのために、ECMAScript 第 6 版で指定された codePointAt() 関数を含むように String を拡張します。

/*! https://mths.be/codepointat v0.1.0 by @mathias */
if (!String.prototype.codePointAt) {
  (function() {
    'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
    var codePointAt = function(position) {
      if (this == null) {
        throw TypeError();
      }
      var string = String(this);
      var size = string.length;
      // `ToInteger`
      var index = position ? Number(position) : 0;
      if (index != index) { // better `isNaN`
        index = 0;
      }
      // Account for out-of-bounds indices:
      if (index < 0 || index >= size) {
        return undefined;
      }
      // Get the first code unit
      var first = string.charCodeAt(index);
      var second;
      if ( // check if it’s the start of a surrogate pair
        first >= 0xD800 && first <= 0xDBFF && // high surrogate
        size > index + 1 // there is a next code unit
      ) {
        second = string.charCodeAt(index + 1);
        if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
          // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
          return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
        }
      }
      return first;
    };
    if (Object.defineProperty) {
      Object.defineProperty(String.prototype, 'codePointAt', {
        'value': codePointAt,
        'configurable': true,
        'writable': true
      });
    } else {
      String.prototype.codePointAt = codePointAt;
    }
  }());
}

仕様

仕様 ステータス コメント
ECMAScript 2015 (6th Edition, ECMA-262)
String.prototype.codePointAt の定義
標準 初期定義。
ECMAScript 2017 Draft (ECMA-262)
String.prototype.codePointAt の定義
ドラフト

ブラウザ実装状況

機能 Chrome Firefox (Gecko) Internet Explorer Opera Safari
基本サポート 41 29 (29) 11 28 未サポート
機能 Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
基本サポート 未サポート 未サポート 29.0 (29) 未サポート 未サポート 未サポート

関連情報

ドキュメントのタグと貢献者

 このページの貢献者: YuichiNukiyama, shide55
 最終更新者: YuichiNukiyama,