JS: String.prototype.codePointAt

By Xah Lee. Date: . Last updated: .

New in ES2015.

s.codePointAt ( pos )

Return a integer that's the codepoint of character at position pos of s.

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

console.log ( "😂".codePointAt (0) === 128514 );
// true

codePointAt Polyfill

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: Character, Code Unit, Code Point
  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
  9. JS: Unicode Escape Sequence

JS String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Code Point
  4. String Escape Sequence
  5. Unicode Escape Sequence
  6. String to Number
  7. Encode URL, Escape String
  8. Format Number
  9. Source Code Encoding
  10. Allowed Characters in Identifier
  11. String Object
  12. String.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog