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?