JS: String.prototype.codePointAt

By Xah Lee. Date: . Last updated: .

New in ES2015.

String.prototype.codePointAt ( pos )

Returns the code point of character at position pos of s.

console.log ( "abc".charCodeAt(0) ); // 97
console.log ( "abc".codePointAt (0) ); // 97

console.log ( "😸".charCodeAt(0) ); // 55357
console.log ( "😸".codePointAt (0) ); // 128568

Old Browser Fix

if ( ! String.prototype.codePointAt ) {

    String.prototype.codePointAt = function fixedCharCodeAt (idx) {
        // 2017-02-24 from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/charCodeAt
        // 2017-02-24 xah lee, made to be compatible with es2015 codePointAt
        // ex. fixedCharCodeAt ('\uD800\uDC00', 0); // 65536
        // ex. fixedCharCodeAt ('\uD800\uDC00', 1); // 65536
        idx = idx || 0
        var code = this.charCodeAt(idx)
        var hi, low
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
            hi = code
            low = this.charCodeAt(idx+1)
            if (isNaN(low)) {
                throw 'High surrogate not followed by low surrogate in fixedCharCodeAt()'
            }
            return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000
        }
        if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            // We return false to allow loops to skip this iteration since should have already handled high surrogate above in the previous iteration
            return false
            /*hi = this.charCodeAt(idx-1)
              low = code
              return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;*/
        }
        return code
    };

}

// test
console.log ( "😸".codePointAt (0) === 128568 ); // true

Reference

ECMAScript 2015 §Text Processing#sec-string.prototype.codepointat

Character Topic

  1. JS: String is 16-Bit Unit Sequence
  2. JS: Convert Character To/From Codepoint
  3. JS: String.fromCodePoint
  4. JS: String.fromCharCode
  5. JS: String.prototype.charAt
  6. JS: String.prototype.charCodeAt
  7. JS: String.prototype.codePointAt
  8. JS: Convert Decimal/Hexadecimal

String Topic

  1. JS: Default Charset/Encoding
  2. JS: String is 16-Bit Unit Sequence
  3. JS: Unicode Character Escape Sequence
  4. JS: Allowed Characters in Identifier
  5. HTML: Allowed Characters in id Attribute
  6. HTML: Character Sets and Encoding
  7. HTML/XML Entity List

  1. JS: Template String
  2. JS: Convert String to Number
  3. JavaScript Encode URL, Escape String
  4. JS: Format Number
  5. JS: JSON Object

  1. JS: String Object
  2. JS: String.prototype
  3. JS: String Constructor
Like what you read? Buy JavaScript in Depth