string.charCodeAt
์ฃผ์ด์ง ์ธ๋ฑ์ค์ ๋ํ UTF-16 code unit์ ๋ํ๋ด๋ 0 - 65535์ฌ์ด์ ์ ์๋ฅผ ๋ฐํํ๋ค.
const sentence = "dhgn gkstl dhtlqtkqns";
const index = 4;
console.log(`index: ${index}, ${sentence.charCodeAt(index)}`); // index: 4, 32
UTF-16 ์ฝ๋ ๋จ์๋ single UTF-16 ์ฝ๋ ๋จ์๋ก ํํํ ์ ์๋ ์ฝ๋ ํฌ์ธํธ์ Unicode ์ฝ๋ ํฌ์ธํธ์ ์ผ์นํ์ง๋ง, Unicode ์ฝ๋ ํฌ์ธํธ๋ฅผ UTF-16 ์ฝ๋ ๋จ์๋ก ๋ํ๋ผ ์ ์๋ค๋ฉด (๊ฐ์ด 0x10000๋ณด๋ค ํฌ๊ธฐ ๋๋ฌธ์) ์ฝ๋ ํฌ์ธํธ์ surrogate pair ์ฒซ๋ฒ์งธ part๋ฅผ ๋ฐํํ๋ค. ์ ์ฒด ์ฝ๋ ํฌ์ธํธ ๊ฐ์ ์ํ๋ค๋ฉด codePointAt()
์ ์ฌ์ฉํ๋ค.
Syntax
str.charCodeAt(index)
Parameters
index
0๋ณด๋ค ๊ฐ๊ฑฐ๋ ํฌ๊ณ , string์ length๋ณด๋ค ์์ ์ ์, number๊ฐ ์๋๊ฒฝ์ฐ default๋ 0์ด๋ค.
Return value
์ฃผ์ด์ง index์ ๋ํ ๋ฌธ์์ UTF-16 code unit ๊ฐ๋ฅผ ๋ํ๋ธ ์ซ์
index๊ฐ ๋ฒ์๋ฐ์ ๋์์ ๋ NaN
Description
Unicode code point ๋ฒ์๋ 0์์ 1114111 (0x10FFFF)๊น์ง์ด๋ค.
์์ชฝ 128 Unicode ์ฝ๋ ํฌ์ธํธ๋ ASCII ๋ฌธ์ ์ธ์ฝ๋ฉ์ ๋์๋๋ค. https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Unicode
charCodeAt()๋ 65536๋ณด๋ค ์์ ๊ฐ์ ํญ์ ๋ฐํํ๋ค.
higher code points๋ surrogate pair๋ก ๋ํ๋ธ๋ค. 65536์ด์์ธ ๊ฐ๋ณ ๋ฌธ์๋ ์ ์ฒด ๋ฌธ์๋ฅผ ๊ฒ์ฌํ๊ฑฐ๋ charCodeAt(i)
์ charCodeAt(i+1)
๋ ๋ฌธ์๋ฅผ ๊ฒ์ฌํด์ผํ๋ค.
์ด๋ด๋ codePointAt(i)๋ฅผ ์ฌ์ฉํ๋ค.
Examples
using charCodeAt()
'ABC'.charCodeAt(0); // A์ Unicode ๊ฐ์ธ 65๋ฅผ return ํ๋ค.
๋ฌธ์์ด์ ์ด์ ๋ถ๋ถ์ "๋ค๊ตญ์ด ๊ธฐ๋ณธํ๋ฉด์ด ์๋ ๋ฌธ์"๊ฐ ์กด์ฌํ๋ค๋ ๊ฒ์ ์์ง ๋ชปํ ๋
for ๋ฃจํ ๋ฑ์ ์ฌ์ฉ๋ ์ ์๋ค.
function fixedCharCodeAt(str, idx) {
// ex. fixedCharCodeAt('\uD800\uDC00', 0); // 65536
// ex. fixedCharCodeAt('\uD800\uDC00', 1); // false ์์ ์๋ ๊ฒฝ์ฐ false
idx = idx || 0;
let code = str.charCodeAt(idx);
let hi, low;
// High surrogate
if (0xD800 <= code && code <= 0xDBFF) {
hi = code;
low = str.charCodeAt(idx + 1);
if (isNaN(low)) {
throw 'High surrogate not followed by ' +
'low surrogate in fixedCharCodeAt()';
}
return ((hi - 0xD800) * 0x400) +
(low - 0xDC00) + 0x10000;
}
// Low surrogate์ผ ๊ฒฝ์ฐ ์๋ถ๋ถ์ non-BMP๊ฐ ์กด์ฌํ๋ ๊ฒฝ์ฐ
if(0xDC00 <= code && code <= 0xDFFF) return false;
return code;
}
๋ฌธ์์ด์ ์ด์ ๋ถ๋ถ์ "๋ค๊ตญ์ด ๊ธฐ๋ณธํ๋ฉด์ด ์๋ ๋ฌธ์"๊ฐ ์กด์ฌํ๋ค๋ ๊ฒ์ ์ ๋
function knownCharCodeAt(str, idx) {
str += '';
let code,
end = str.length;
let surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
while ((surrogatePairs.exec(str)) != null) {
let li = surrogatePairs.lastIndex;
if (li - 2 < idx) {
idx++;
} else {
break;
}
}
if (idx >= end || idx < 0) return NaN;
code = str.charCodeAt(idx);
let hi, low;
// surrogate pair
if (0xD800 <= code && code <= 0xDBFF) {
hi = code;
low = str.charCodeAt(idx + 1);
return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
}
return code;
}
๐ค
Last updated
Was this helpful?