์ ์ String.fromCodePoint()
๋ฉ์๋๋ ์ฝ๋ ํฌ์ธํธ ์ํ์ค๋ฅผ ์ด์ฉํ์ฌ ๋ฌธ์์ด์ ์์ฑํด ๋ฐํํ๋ค.
String.fromCodePoint(9731, 9733, 9842, 0x2F804) // "โโ
โฒไฝ "
Syntax
String.fromCodePoint(num1, [, ...[ numN ]])
Parameters
num1, ..., numN
์ฝ๋ ํฌ์ธํธ์ ์ํ์ค
Return value
์ฝ๋ ํฌ์ธํธ์ ์ํ์ค๋ฅผ ์ด์ฉํด ์์ฑํ ๋ฌธ์์ด
Exceptions
์ ํจํ์ง ์์ ์ ๋์ฝ๋ ์ฝ๋ํฌ์ธํธ๋ฅผ ๋๊ธด๋ค๋ฉด RangeError ("RangeError: NaN is not a valid code point")
Description
์ด ๋ฉ์๋๋ String object๊ฐ ์๋ string์ returnํ๋ค. fromCodePoint()
๋ String์ ์ ์ ๋ฉ์๋์ด๊ธฐ ๋๋ฌธ์ด๋ค. ์ค์ค๋ก ์์ฑํ String object ๋ฉ์๋๊ฐ ์๋๋ผ ํญ์ String.fromCodePoint()๋ก ์ฌ์ฉํ๋ค.
Example
fromCodePoint() ์ฌ์ฉํ๊ธฐ
String.fromCodePoint(42); // "*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // "\u0404" -> "ะ"
String.fromCodePoint(0x2F804); // "\uD87E\uDC04" -> "ไฝ "
String.fromCodePoint(194564); // "\uD87E\uDC04" -> "ไฝ "
String.fromCodePoint(0x1D306, 0x61, 0x1D307); // "๐a๐"
์ ํจํ์ง ์์ input
String.fromCodePoint('_'); // RangeError: Invalid code point NaN
// at Function.fromCodePoint (<anonymous>)
// at <anonymous>:1:8
fromCharCode()์ ๋น๊ต
String.fromCharCode()๋ ์ฝ๋ ํฌ์ธํธ๋ฅผ ์ง์ ํ์ฌ 0x010000 โ 0x10FFFF๋ฅผ ๋ฐํํ ์ ์๋ค. ๋์ ๋ฐํํ๋ ค๋ฉด UTF-16์ surrogate pair๊ฐ ํ์ํ๋ค.
String.fromCharCode(0xD83C, 0xDF03); // "๐"
String.fromCharCode(55356, 57091); // "๐"
๋ฐ๋ฉด String.fromCodePoint()๋ UTF-32 ์ฝ๋ ์ ๋์ ํด๋นํ๋ ์ฝ๋ ํฌ์ธํธ๋ฅผ ์ง์ ํ์ฌ 4-byte ๋ณด์กฐ ๋ฌธ์์ด๊ณผ ์ผ๋ฐ์ ์ธ 2๋ฐ์ดํธ BMP ๋ฌธ์๋ฅผ ๋ฐํํ ์ ์๋ค.
String.fromCodePoint(0x1F303); // "๐"
Polyfill
IE์์๋ ์ ํ ์ง์์ด ์๋๋ค.
if(!String.fromCodePoint) (function(stringFromCharCode) {
var fromCodePoint = function(_) {
var codeUnits = [], codeLen = 0, result = '';
for (var index = 0, len = arguments.length; index !== len; ++index) {
var codePoint = +arguments[index];
// `NaN`, `-Infinity`, `+Infinity` ํฌํจ๋ ๋ชจ๋ ์ผ์ด์ค๋ฅผ ์ฒ๋ฆฌ
// NaN ์ผ์ด์ค๋ฅผ ์ฒ๋ฆฌํ๋ ค๋ฉด `!(...)` ํ์
// (codePoint>>0) === codePoint ์์์ ๊ณผ negatives ์ฒ๋ฆฌ
if (!(codePoint < 0x10FFFF && (codePoint>>>0) === codePoint))
throw RangeError("Invalid code point: " + codePoint);
if (codePoint <= 0xFFFF) { // BMP code point
codeLen = codeUnits.push(codePoint);
} else { // Astral code point; surrogate๋ฅผ ๋ถํ
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint = codeUnits.push(
(codePoint >> 10) + 0xD800, // high Surrogate
(codePoint % 0x400) + 0xDC00 // low Surrogate
)
}
if (codeLen >= 0x3fff) {
result += stringFromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result + stringFromCahrCode.apply(null, codeUnits);
};
try { // DOM element `Object.defineProperty` IE 8 ์ํฌํธ
Object.definePropery(String, "fromCodePoint", {
"value": fromCodePoint, "configurable": true, "writable": true
});
} catch (e) {
String.fromCodePoint = fromCodePoint;
}
}(String.fromCharCode));