JS: String.prototype.codePointAt

By Xah Lee. Date: . Last updated: .

New in ES2015.

str.codePointAt ( pos )

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

console.log ( "abc".codePointAt (0) === 97 ); // true
// char a has unicode codepoint 97
console.log ( "😂".codePointAt (0) === 128514 ); // true

// 😂
// name: FACE WITH TEARS OF JOY
// codepoint decimal: 128514
// codepoint hexadecimal: 1f602
// UTF8 encoding: F0 9F 98 82
// Utf16 encoding: D8 3D DE 02

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

JS Character

  1. Character, Code Unit, Codepoint
  2. Character To/From Codepoint
  3. String.fromCodePoint
  4. String.fromCharCode
  5. String.prototype.charAt
  6. String.prototype.charCodeAt
  7. String.prototype.codePointAt
  8. Convert Decimal/Hex
  9. Unicode Escape Sequence

JS String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Codepoint
  4. String Escape Sequence
  5. Unicode Escape Sequence

Like it? Help me by telling your friends. Or, 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 Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog