DEV Community

Cover image for JavaScript: O que é Intl?
Cristian Magalhães
Cristian Magalhães

Posted on • Edited on

2

JavaScript: O que é Intl?

O Intl é uma API de internacionalização do próprio JavaScript aqui vou falar um pouco mais sobre ela.

Como usar?

Basicamente você cria uma nova instância do Intl com o tipo de formatador que você deseja utilizar, passando a localidade como parâmetro e suas configurações e simplesmente sai usando sendo feliz.

Agora vamos dar uma olhada em algumas opções dessa API.

Collator

Segundo o MDN "O objeto collator permite a comparação de cadeia sensível à linguagem.", porém eu achei um pouco confuso, pesquisando um pouco mais encontrei algo que possa ajudar melhor "O objeto intl.collator permite que você compare string em relação á nacionalidade e internacionalização". Ou seja, nós podemos usar o Intl.Collator, para comparar strings especiais de localidades diferentes.

Achei um exemplo que deixa isso bem mais claro, vamos lá. No alfabeto alemão a letra ä vem depois do a, porém no alfabeto sueco ela vem no final do alfabeto, depois da letra z

console.log(['b', 'a', 'z', 'ä'].sort(new Intl.Collator('de').compare));
console.log(['b', 'a', 'z', 'ä'].sort(new Intl.Collator('sv').compare));
Enter fullscreen mode Exit fullscreen mode

e o resultado então é:

['a', 'ä', 'b', 'z']
['a', 'b', 'z', 'ä']
Enter fullscreen mode Exit fullscreen mode

Por fim a string que o Intl.Collator recebe como paramêtro é uma tag para a abreviação de alguns idiomas.

  • ar — Arabic
  • bg — Bulgarian
  • ca — Catalan
  • zh-Hans — Chinese, Han (Simplified variant)
  • cs — Czech
  • da — Danish
  • de — German
  • el — Modern Greek (1453 and later)
  • en — English
  • es — Spanish
  • fi — Finnish
  • fr — French
  • he — Hebrew
  • hu — Hungarian
  • is — Icelandic
  • it — Italian
  • ja — Japanese
  • ko — Korean
  • nl — Dutch
  • no — Norwegian
  • pl — Polish
  • pt — Portuguese
  • rm — Romansh
  • ro — Romanian
  • ru — Russian
  • hr — Croatian
  • sk — Slovak
  • sq — Albanian
  • sv — Swedish
  • th — Thai
  • tr — Turkish
  • ur — Urdu
  • id — Indonesian
  • uk — Ukrainian
  • be — Belarusian
  • sl — Slovenian
  • et — Estonian
  • lv — Latvian
  • lt — Lithuanian
  • tg — Tajik
  • fa — Persian
  • vi — Vietnamese
  • hy — Armenian
  • az — Azerbaijani
  • eu — Basque
  • hsb — Upper Sorbian
  • mk — Macedonian
  • tn — Tswana
  • xh — Xhosa
  • zu — Zulu
  • af — Afrikaans
  • ka — Georgian
  • fo — Faroese
  • hi — Hindi
  • mt — Maltese
  • se — Northern Sami
  • ga — Irish
  • ms — Malay (macrolanguage)
  • kk — Kazakh
  • ky — Kirghiz
  • sw — Swahili (macrolanguage)
  • tk — Turkmen
  • uz — Uzbek
  • tt — Tatar
  • bn — Bengali
  • pa — Panjabi
  • gu — Gujarati
  • or — Oriya
  • ta — Tamil
  • te — Telugu
  • kn — Kannada
  • ml — Malayalam
  • as — Assamese
  • mr — Marathi
  • sa — Sanskrit
  • mn — Mongolian
  • bo — Tibetan
  • cy — Welsh
  • km — Central Khmer
  • lo — Lao
  • gl — Galician
  • kok — Konkani (macrolanguage)
  • syr — Syriac
  • si — Sinhala
  • iu — Inuktitut
  • am — Amharic
  • tzm — Central Atlas Tamazight
  • ne — Nepali
  • fy — Western Frisian
  • ps — Pushto
  • fil — Filipino
  • dv — Dhivehi
  • ha — Hausa
  • yo — Yoruba
  • quz — Cusco Quechua
  • nso — Pedi
  • ba — Bashkir
  • lb — Luxembourgish
  • kl — Kalaallisut
  • ig — Igbo
  • ii — Sichuan Yi
  • arn — Mapudungun
  • moh — Mohawk
  • br — Breton
  • ug — Uighur
  • mi — Maori
  • oc — Occitan (post 1500)
  • co — Corsican
  • gsw — Swiss German
  • sah — Yakut
  • qut — Guatemala
  • rw — Kinyarwanda
  • wo — Wolof
  • prs — Dari
  • gd — Scottish Gaelic

Lista retirada do artigo Comparing Non-English Strings with JavaScript Collators

DateTimeFormat

O nome desse método já diz tudo. Bom ele basicamente serve para formatar uma data de acordo com a localização. Ele tem várias opções que você pode usar para configurar a data do jeito que precisar.

Confesso que fiquei surpreso com as possibilidades

Abaixo alguns exemplos:

console.log(new Intl.DateTimeFormat(['pt-BR'], {
    dateStyle: 'full',
    //opções...
}).format(new Date()));
// domingo, 29 de janeiro de 2023
console.log(new Intl.DateTimeFormat(['pt-BR'], {
    dateStyle: 'long',
}).format(new Date()));
// 29 de janeiro de 2023
console.log(new Intl.DateTimeFormat(['pt-BR'], {
    dayPeriod: "long"
}).format(new Date()));
// da tarde
console.log(new Intl.DateTimeFormat(['en-US'], {
    dateStyle: 'full'
}).format(new Date()));
// Sunday, January 29, 2023
Enter fullscreen mode Exit fullscreen mode

DisplayNames

O Intl.DisplayNames faz traduções consistentes de region, script, dateTimeField, language e currency. Abaixo alguns exemplos e como cada um funciona:

region

const regionNamesInEnglish = new Intl.DisplayNames(['en'], { type: 'region' });
console.log(regionNamesInEnglish.of('US'));
// United States
Enter fullscreen mode Exit fullscreen mode

dateTimeField

const dateTimeFieldInPortuguese = new Intl.DisplayNames(['pt-BR'], { type: 'dateTimeField' });
console.log(dateTimeFieldInPortuguese.of('month'));
// mês
Enter fullscreen mode Exit fullscreen mode

language
Nesse caso deve usar o código da linguagem. Aqui você encontra mais detalhes sobre

const langueInPortuguese = new Intl.DisplayNames(['pt-BR'], { type: 'language' });
console.log(langueInPortuguese.of('fr'));
// francês
Enter fullscreen mode Exit fullscreen mode

currency
Aqui você passa como parâmetro o currency code da moeda desejada.

const currencyInPortuguese = new Intl.DisplayNames(['pt-BR'], { type: 'currency' });
console.log(currencyInPortuguese.of('EUR'));
// Euro
Enter fullscreen mode Exit fullscreen mode

Como são muitos detalhes não vou conseguir abordar todos aqui, mas caso tenha curiosidade neste link tem mais alguns detalhes sobre o uso do Intl.DisplayNames.

NumberFormat

O nome da função Intl.NumberFormat é bem auto explicativo também, ele formata números moedas e afins. Abaixo eu deixei alguns exemplos de uso:

const number = 1273162.12

const formatterBR = new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL'
});
console.log(formatterBR.format(number))
// R$ 1.273.162,12

const formatterJP = new Intl.NumberFormat('ja-JP', {
    style: 'currency',
    currency: 'JPY'
})

console.log(formatterJP.format(number))
// ¥1,273,162
Enter fullscreen mode Exit fullscreen mode

RelativeTimeFormat

O objetivo do Intl.RelativeTimeFormaté formatar uma passagem de tempo e trazer para a linguagem passada por parâmetro. Como no exemplo abaixo:

const formatterBR = new Intl.RelativeTimeFormat('pt-BR', {
    style: 'narrow'
});

const formatterEN = new Intl.RelativeTimeFormat('en', {
    style: 'narrow'
});

console.log(formatterBR.format(1, 'day'))  // em 1 dia
console.log(formatterBR.format(-1, 'day')) // há 1 dia
console.log(formatterEN.format(1, 'day')) // in 1 day
console.log(formatterEN.format(-1, 'day')) // 1 day ago
Enter fullscreen mode Exit fullscreen mode

Ponto importante

A api do Intl tem mais alguns métodos que não abordei aqui. Resolvi apenas trazer os que achei mais interessantes e úteis, todas as opções abordadas tem várias opções de configuração, a ideia é apenas te dar um overview e trazer para o conhecimento de vocês a existência dessa API e evitar criar funções na mão, igual alguém aqui fez...

Muito obrigado por ler 🙃

Minhas redes sociais

Referências

JavaScript Interview Question #50: How does Intl.Collator work in JS
by Coderslang: Become a Software Engineer

Comparing Non-English Strings with JavaScript Collators

MDN Docs

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (3)

Collapse
 
allandrscode profile image
Allan Douglas

Obrigado !

Collapse
 
gomesgbr profile image
Gabriel Gomes

Muito bom post, explicação simples e direta, recurso extremamente útil. Obrigado!

Collapse
 
cristuker profile image
Cristian Magalhães

Obrigado <3

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️