일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 디자인
- 제로베이스 프론트엔드 스쿨
- 프로그래머스
- TypeScript
- JavaScript
- 정규표현식
- 비트연산자
- 웹접근성
- leetcode
- 카드뉴스
- programmers
- react
- wai-aria
- react-query
- html&css
- 알고리즘
- Today
- Total
記錄
Intl (internationalization) API 본문
00. Intl API 란
Intl 객체는 각 언어에 맞는 문자비교, 숫자, 시간, 날짜비교를 제공하는, ECMAScript 국제화 API를 위한 이름공간이다. 여러 가지 언어로 서비스를 할 수 있도록(국제화, internalization) 웹페이지 상에 사용된 문구와 데이터를 언어나 지역별로 다른 형식으로 보여줄 수 있게 해준다.
외부 라이브러리를 사용하지 않고도 자바스크립트에서 제공하는 Intl API를 사용해 다국어 지원을 하는 서비스에서 데이터를 하나 하나 번역하지 않고도 언어 처리를 할 수 있어 유용하게 사용할 수 있다.
기본적인 사용 방법
기본 형태에 locales 매개변수를 추가해 적절한 언어를 제공할 수 있다.
navigator.language 를 이용해 사용자가 설정한 언어 자동으로 읽어와서 적용할 수 있다.
var number = 3500;
console.log(new Intl.NumberFormat().format(number));
// → 한국 로케일의 경우 '3,500' 표시
01. 숫자 표현 - NumberFormat()
통화, 백분율, 무게, 길이, 속도, 온도 등 단위가 있는 숫자 데이터를 다룰 때 사용한다.
style 옵션을 통해 다양한 스타일을 지원한다.
예를 들어 유튜브 조회수 단위 표시, 트위터 RT 수 등을 간략하게 표현할 때 사용할 수 있다.
숫자 단위 데이터 표현
//백분율
new Intl.NumberFormat('ko', { style: 'percent' }).format(0.7)
'70%'
new Intl.NumberFormat('ko', { style: 'percent' }).format(1 / 4)
'25%'
//숫자 단위 간결하게 표현
const views=9744642
const formatter=new Intl.NumberFormat('ko')
formatter.format(views) -//콤마 찍힘 9,744,642
const formatter=new Intl.NumberFormat('ko',{ notation:'compact' })
//974만
const formatter=new Intl.NumberFormat('en',{ notation:'compact' })
//9.7M
const formatter=new Intl.NumberFormat('en',{
notation:'compact',
compactDisplay:'long',
})
//9.7 million
/*
compactDisplay 옵션은 notation:'compact'과 함께 사용해야 함
short(default), long 으로 설정 가능함
*/
통화(currency) 표현
const price=10000
const formatter=new Intl.NumberFormat('ko-KR',{
style:'currency',
currency:'krw',
notation:'compact'
})
//₩10000
const formatter=new Intl.NumberFormat('en-US',{
style:'currency',
currency:'usd',
notation:'compact'
})
formatter.format(price)
//$10000
보다 많은 option들은 관련 MDN 링크를 참고해서 활용하자.
Intl.NumberFormat() constructor - JavaScript | MDN
The Intl.NumberFormat() constructor creates Intl.NumberFormat objects that enable language-sensitive number formatting.
developer.mozilla.org
02. 날짜 표현 - DateTimeFormat()
시간이나 날짜를 언어나 지역에 따라 다르게 표시할 수 있다.
주로 dateStyle과 timeStyle을 이용해 full, long, medium, short 옵션을 설정해 표현 가능하다.
const date=new Date(2019,10,12) //2019/11/12
new Intl.DateTimeFormat('en-US').format(date) // 2019.11.12
date.toLocaleDateString() //11/12/2019
date.toLocaleDateString('ko') //2019.11.12
date.toLocaleDateString('ko', {
dateStyle:'full',
timeStyle:'long',
})//2019년 11월 12일 화요일 오전 12시 0분 0초 GMT+9
new Intl.DateTimeFormat("ko", { dateStyle: 'full' }).format(new Date())
'2022년 3월 8일 화요일'
new Intl.DateTimeFormat("ko", { dateStyle: 'long' }).format(new Date())
'2022년 3월 8일'
new Intl.DateTimeFormat("ko", { dateStyle: 'medium' }).format(new Date())
'2022. 3. 8.'
new Intl.DateTimeFormat("ko", { dateStyle: 'short' }).format(new Date())
'22. 3. 8.'
세부 옵션
property | description |
timeZone | time zone: "UTC", "America/New_York" "Europe/Paris" etc. |
calendar | options include: "chinese" "gregory" "hebrew" "indian" "islamic" etc. |
numberingSystem | numbering system: "arab" "beng" "fullwide" "latn" etc. |
localeMatcher | locale matching algorithm: "lookup" "best fit" |
formatMatcher | format matching algorithm: "basic" "best fit" |
hour12 | set true to use 12-hour time notation |
hourCycle | hour cycle: "h11" "h12" "h23" "h24" |
dateStyle | the date style: "full" "long" "medium" "short" |
weekday | weekday format: "long" "short" "narrow" |
day | day format: "numeric" "2-digit" |
month | month format: "numeric" "2-digit" "long" "short" "narrow" |
year | year format: "numeric" "2-digit" |
era | era format (AD, BC): "long" "short" "narrow" |
timeStyle | the time style: "full" "long" "medium" "short" |
hour | hour format: "numeric" "2-digit" |
minute | minute format: "numeric" "2-digit" |
second | second format: "numeric" "2-digit" |
dayPeriod | period expressions (morning, night, noon): "narrow" "short" "long" |
timeZoneName | (UTC, PTC) either: "long" "short" |
date.toLocaleDateString('ko', {
minute:'numeric',
hour: 'numeric',
day:'numeric',
month:'short',
year:'numeric',
weekday:'long',
})
03. 상대 시간 표시 - RelativeTimeFormat()
상대시간(몇시간 전,몇 초 전, 몇 년 전에 올라왔는지)을 지정한 언어에 따라 표현 가능하다.
예를 들어, 유튜브에서 자주 볼 수 있는 "몇 시간 전", "3주 전" 등으로 나타내고자 할 때 사용할 수 있다.
const formatter=new Intl.RelativeTimeFormat('en')
formatter.format(1,'day') //첫번째 인자: 숫자, 두번째 인자:날짜인지 시간인지 달인지 명시 가능
formatter.format(1,'day') //in 1 day
formatter.format(2,'day') //in 2 days
formatter.format(-1,'day') //1 day ago
formatter.format(-2,'day') //2 days ago
numeric 옵션 추가
const formatter=new Intl.RelativeTimeFormat('en', { numeric : auto })
formatter.format(1,'day') //tomorrow
formatter.format(-1,'day') //yesterday
언어를 한국어로 변경
const formatter=new Intl.RelativeTimeFormat('ko', { numeric : auto })
formatter.format(1,'day') //내일
formatter.format(2,'day') //모레
formatter.format(-1,'day') //어제
formatter.format(-2,'day') //그저께
시간과 날짜를 함께 포맷팅
// French custom date and time: "mardi 04 mai 2021 à 13 h"
new Intl.DateTimeFormat(
"fr-FR",
{
"weekday": "long",
"day": "2-digit",
"month": "long",
"year": "numeric",
"hour": "2-digit"
}
).format( new Date("2022-05-04T13:00") );
* 상대 시간 표현 라이브러리 : timeago.js
상대적인 시간을 제공해주기만 해도 seconds, hours, days, weeks, years 단위로 변환해준다.
npm install timeago.js
<script src="dist/timeago.min.js"></script>
//cdn
<script src="//unpkg.com/timeago.js"></script>
//설치 또는 cdn 링크 넣은 뒤 format('2016-06-12','en_US')->이런식으로 쓰면 알아서 바꿔줌
04. 리스트 표현 - ListFormat()
여러 개의 데이터를 로케일에 따라 다르게 나타낼 때 사용할 수 있다.
type 옵션으로 논리곱(conjunction) 형태 또는 논리합(disjunction) 형태로 이어줄 지 설정할 수 있다.
//type: conjuction (기본값)
new Intl.ListFormat('en').format(['Chrome', 'Safari', 'Firefox'])
'Chrome, Safari, and Firefox'
new Intl.ListFormat('ko').format(['크롬', '사파리', '파이어폭스'])
'크롬, 사파리 및 파이어폭스'
//type: disjunction
new Intl.ListFormat('en', { type: 'disjunction' }).format(['Chrome', 'Safari', 'Firefox'])
'Chrome, Safari, or Firefox'
new Intl.ListFormat('ko', { type: 'disjunction' }).format(['크롬', '사파리', '파이어폭스'])
'크롬, 사파리 또는 파이어폭스'
05. 단복수 처리 - PluralRules()
영어와 같이 단복수를 엄격하게 구분하는 언어에서 숫자 다음에 나오는 명사의 단복수 처리를 할 때 사용한다.
PluralRules() 생성자로 만든 객체의 select() 함수에 숫자를 넘기면 "one" 또는 "other"이 반환되는데, 이 결과 값으로 단수형 명사를 사용할 지 복수형 명사를 사용할 지 판단할 수 있다.
type 옵션의 기본값은 "cardinal"이고, "ordinal"로 변경하면 영어에서 필요한 서수(nd, th 같은)의 어미 처리를 할 수 있다.
let pr = new Intl.PluralRules("en")
undefined
> pr.select(0)
'other'
> pr.select(1)
'one'
> pr.select(2)
'other'
> pr.select(3)
'other'
> pr.select(4)
//type: "ordinal"이면 one=>1st, two=>2nd, other=>nth 식으로 반환
참고 자료
https://www.youtube.com/watch?v=2AMRTAFSh98
https://www.youtube.com/watch?v=4YnKQrPMTNU
https://www.daleseo.com/js-intl-api/
+
참고한 영상이 올라오기 이전에 관련 정보를 SNS에서 보기도 했고, 알아두면 유용하게 쓰일 것 같아 따로 정리했다.
'FRONTEND STUDY > JavaScript' 카테고리의 다른 글
TypeScript 요약 - 1 (0) | 2022.12.11 |
---|---|
this (0) | 2022.12.04 |
Cookie, LocalStorage, SessionStorage (0) | 2022.11.20 |
정규표현식 Regex (0) | 2022.11.13 |
JavaScript 함수/조건문/반복문 (0) | 2022.10.30 |