JavaScript Intlで世界を広げる:国際化対応を実現する方法
- 作成日 2024.12.11
- javascript
- javascript
JavaScriptのIntlオブジェクトを使用することで、アプリケーションを国際化し、異なる地域のユーザーに合わせた表示を行うことができます。本記事では、Intlを活用して国際化対応を行う方法を、さまざまな機能とともに解説します。
Intlオブジェクトの基本概要
Intlは、国際化に関する機能を提供するJavaScriptの組み込みオブジェクトです。日付や数値、通貨のフォーマットなど、ローカライズされた操作を簡単に実行できます。
Intl.DateTimeFormatで日付のローカライズ
Intl.DateTimeFormatを使用して、日付と時刻を異なる地域に合わせてフォーマットできます。
const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US');
console.log(formatter.format(date)); // "12/11/2024"
異なるロケールでの日付表示
特定のロケールに基づいて、日付や時刻を表示できます。
const date = new Date();
const formatter = new Intl.DateTimeFormat('de-DE');
console.log(formatter.format(date)); // "11.12.2024"
Intl.NumberFormatで数値をローカライズ
Intl.NumberFormatを使用すると、数値をローカライズして表示できます。これにより、異なる地域での小数点の使い方や桁区切りに対応できます。
const number = 1234567.89;
const formatter = new Intl.NumberFormat('en-US');
console.log(formatter.format(number)); // "1,234,567.89"
通貨のローカライズ
通貨をローカライズして表示するために、Intl.NumberFormatを使って簡単に対応できます。
const price = 199.99;
const currencyFormatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
console.log(currencyFormatter.format(price)); // "$199.99"
国際化対応した比較機能:Intl.Collator
Intl.Collatorを使って、ローカライズされた文字列の比較が行えます。これにより、アルファベット順や数値順に正確に並べ替えができます。
const collator = new Intl.Collator('en-US');
console.log(collator.compare('apple', 'banana')); // -1
言語コードとロケールの指定方法
Intlオブジェクトで使用するロケールコードには、言語コードと地域コードを組み合わせた形式を指定します。これにより、適切なフォーマットが選ばれます。
const formatter = new Intl.DateTimeFormat('fr-FR');
console.log(formatter.format(date)); // "11/12/2024"
タイムゾーンの指定
Intl.DateTimeFormatではタイムゾーンを指定して、異なるタイムゾーンのユーザーに対応した日付や時刻を表示することができます。
const formatter = new Intl.DateTimeFormat('en-US', { timeZone: 'Europe/London' });
console.log(formatter.format(date)); // ロンドンのタイムゾーンに基づく日付
Intl.RelativeTimeFormatで相対時間の表示
相対的な時間表示(「3時間前」や「昨日」など)を行うためには、Intl.RelativeTimeFormatを使用します。
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
console.log(rtf.format(-1, 'day')); // "yesterday"
Intl.PluralRulesで複数形のローカライズ
Intl.PluralRulesを使うことで、数値に基づいた複数形のルールを適用できます。言語ごとに異なる複数形ルールに対応可能です。
const pluralRule = new Intl.PluralRules('en');
console.log(pluralRule.select(1)); // "one"
console.log(pluralRule.select(2)); // "other"
複数のロケールをサポートする方法
Intlオブジェクトでは、複数のロケールに対応したフォーマットを提供することができます。異なる言語や地域ごとに異なる設定を自動で切り替えることができます。
const formatter = new Intl.NumberFormat(['en-US', 'fr-FR']);
console.log(formatter.format(1234567.89)); // "1,234,567.89" または "1 234 567,89"
Intlを使ったエラーハンドリング
Intlオブジェクトは、無効なロケールコードや設定が与えられた場合に、エラーを返すことがあります。適切なエラーハンドリングを行うことが重要です。
try {
const formatter = new Intl.DateTimeFormat('invalid-locale');
} catch (error) {
console.log('Error:', error.message); // "Unsupported locale"
}
まとめ
JavaScriptのIntlオブジェクトを使うことで、国際化対応を効率的に実現することができます。日付や数値、通貨などをローカライズする機能は、グローバルに展開するアプリケーションには欠かせない要素です。Intlを活用し、さまざまなロケールに対応したアプリケーションを作成してみましょう。
-
前の記事
TypeScriptのNonNullable型でnullableを排除する徹底解説 2024.12.11
-
次の記事
TypeScriptのOmit型で不必要なプロパティを除去するスマートな方法 2024.12.12
コメントを書く