JavaScript의 Intl

SteadySlower·2024년 12월 20일
0

Javascript&TypeScript

목록 보기
1/4
post-thumbnail

예전에 swift를 할 때 어떤 날짜를 오늘과 비교해서 “n일전”과 같은 형태로 변경하기 위해서 직접 구현을 했던 적이 있는데 javascript를 통해서 비슷한 것을 구현 하려다가 Intl이라는 것을 알게 되었다. Intl을 사용하면 “n일전”을 아래와 같이 아주 간단하게 구현 가능하다.

  const formatter = new Intl.RelativeTimeFormat("ko");
  const dayBefore = formatter.format(-3, "days");
  console.log(dayBefore) // 3일전

이 기막힌 편리함에 감탄하며 Intl이라는 API를 좀 더 공부 해보았다.

Intl 객체란?

Intl은 "Internationalization"의 약자로, JavaScript의 국제화 API이다. 숫자, 날짜, 문자열 정렬 등 다양한 작업을 원하는 언어 맞게 지역화된 방식으로 처리할 수 있다. Intl은 다양한 언어를 지원하고 추가 라이브러리가 없이도 동작하기 때문에 빠르고 효율적이다. 한국어와 일본어의 예시로 Intl에 대해 자세히 알아보자!


1. 숫자 포맷 (Intl.NumberFormat)

숫자를 지역화된 방식으로 포맷할 수 있다. 아래는 숫자를 통화 포맷으로 바꾸는 방식이다.

const formatter = new Intl.NumberFormat('ko-KR', {
  style: 'currency',
  currency: 'KRW',
});

console.log(formatter.format(123456.78)); // "₩123,457"

// 일본어 예시
const formatterJP = new Intl.NumberFormat('ja-JP', {
  style: 'currency',
  currency: 'JPY'
});

console.log(formatterJP.format(123456.78)); // "¥123,457"

2. 날짜 및 시간 포맷 (Intl.DateTimeFormat)

날짜와 시간을 지역에 따라 포맷한다. 한국어로 포매팅하면 한글로, 일본어로 포매팅하면 한자로 표시되는 것을 볼 수 있다. 이게 이렇게 간단하게 되다니 놀랍다.

const dateFormatter = new Intl.DateTimeFormat('ko-KR', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long',
});

console.log(dateFormatter.format(new Date())); // "2024년 12월 20일 금요일"

// 일본어 예시
const dateFormatterJP = new Intl.DateTimeFormat('ja-JP', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long',
});

console.log(dateFormatterJP.format(new Date())); // "2024年12月20日金曜日"

3. 문자열 정렬 (Intl.Collator)

문자열을 특정 언어의 정렬 순서에 맞게 정렬할 수 있다. 여기서 sensitivity는 대소문자와 악센트를 구분하는 문자에 사용하는 옵션이라고 한다. 한국어와 일본어는 그런 것이 없으므로 설명은 생략한다.

const collator = new Intl.Collator('ko-KR', { sensitivity: 'base' });

const items = ['가', '하', '나'];
console.log(items.sort(collator.compare)); // ["가", "나", "하"]

// 일본어 예시
const collatorJP = new Intl.Collator('ja-JP', { sensitivity: 'base' });

const itemsJP = ['あ', 'お', 'い'];
console.log(itemsJP.sort(collatorJP.compare)); // ["あ", "い", "お"]

4. 플루럴 규칙 처리 (Intl.PluralRules)

숫자에 따라 복수형 규칙을 처리할 수 있다.

const pluralRules = new Intl.PluralRules('ko-KR');
console.log(pluralRules.select(1)); // "other"
console.log(pluralRules.select(2)); // "other"

// 일본어 예시
const pluralRulesJP = new Intl.PluralRules('ja-JP');
console.log(pluralRulesJP.select(1)); // "other"
console.log(pluralRulesJP.select(2)); // "other"

한국어와 일본어는 모두 복수형 구분이 없으므로 항상 "other"을 반환한다. 어쩔 수 없이 영어의 예시를 보자.

const pluralRulesEn = new Intl.PluralRules('en-US');
console.log(pluralRulesEn.select(1)); // "one"
console.log(pluralRulesEn.select(2)); // "other"

영어에서는 단수와 복수형을 구분하여 "one" 또는 "other"을 반환한다.

profile
백과사전 보다 항해일지(혹은 표류일지)를 지향합니다.

0개의 댓글