string.codePointAt

codePointAt() method๋Š” Unicode code point์Œ์ˆ˜๊ฐ€ ์•„๋‹Œ ์ •์ˆ˜๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.

const icons = 'โ˜ƒโ˜…โ™ฒ';

console.log(icons.codePointAt(1)); // 9733

Syntax

str.codePointAt(pos)

Parameters

pos

code point ๊ฐ’์œผ๋กœ ๋ฐ˜ํ™˜ํ•  String ์š”์†Œ์˜ ์œ„์น˜

Return value

์ฃผ์–ด์ง„ index์˜ code point ๊ฐ’์˜ ๋ฌธ์ž๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆซ์ž,

index์œ„์น˜์— element๊ฐ€ ์—†์„ ๊ฒฝ์šฐ undefined

Description

index์—์„œ surrogate pair์ด ์‹œ์ž‘๋˜์ง€ ์•Š์œผ๋ฉด index ์œ„์น˜์— ์žˆ๋Š” code unit์„ return ํ•œ๋‹ค.

Examples

Using codePointAt()

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

'XYZ'.codePointAt(42); // undefined index์œ„์น˜์— element๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์—

Polyfill

if (!String.prototype.codePointAt) {
  (function() {
        'use strict'; // `undefined`/`null`๊ณผ ํ•จ๊ป˜ `apply`/`call` ์ง€์›ํ•˜๋Š”๋ฐ ํ•„์š”
        var defineProperty = (function() {
      //  IE 8์—์„œ DOM elements์— ๋Œ€ `Object.defineProperty`๋งŒ ์ง€์›
        try {
                var object = {};
          var $defineProperty = Object.defineProperty;
          var result = $defineProperty(object, object, object) && $defineProperty;
        } catch(error) {}
        return result;
        }());

    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;
      }
      if (index < 0 || index >= size) {
        return undefined;
      }
      var first = string.chrCodeAt(index);
      var second;
      // high surrogate์™€ ๋‹ค์Œ index๊ฐ€ ์žˆ๋Š”์ง€ ์ฒดํฌ
      if(first >= 0xD800 && first <= 0xDBFF && size > index + 1) {
        second = string.charCodeAt(index + 1);
        // low surrogate
        if(second >= 0xDC00 && second <= 0xDFFF) {
          return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
        }
      }
      return first;
    }

    if (defineProperty) {
      defineProperty(String.prototype, 'codePointAt', {
        'value': codePointAt,
        'configurable': true,
        'writable': true
      });
    } else {
      String.prototype.codePointAt = codePointAt;
    }
  }());
}

Last updated

Was this helpful?