Intl.ListFormatによるリストフォーマット(And、Or、Unit)
Intl.ListFormatを使用して、配列をロケール対応の文にまとめます。接続詞(and)、選択肢(or)、単位タイプ、およびlong、short、narrowの出力スタイルオプションについて学びます。
Intl.ListFormat
詳細な説明
Intl.ListFormat:ロケール対応のリスト結合
Intl.ListFormatは配列要素を任意のロケールで文法的に正しい文字列に結合します。オックスフォードカンマ、異なる接続詞、さまざまな句読法スタイルを含むリストフォーマットの複雑なルールを処理します。
接続詞(And)
const items = ['Apple', 'Banana', 'Cherry'];
new Intl.ListFormat('en', { type: 'conjunction' })
.format(items); // "Apple, Banana, and Cherry"
new Intl.ListFormat('ja', { type: 'conjunction' })
.format(items); // "Apple、Banana、Cherry"
new Intl.ListFormat('de', { type: 'conjunction' })
.format(items); // "Apple, Banana und Cherry"
選択肢(Or)
new Intl.ListFormat('en', { type: 'disjunction' })
.format(items); // "Apple, Banana, or Cherry"
new Intl.ListFormat('ja', { type: 'disjunction' })
.format(items); // "Apple、Banana、またはCherry"
単位タイプ
new Intl.ListFormat('en', { type: 'unit', style: 'narrow' })
.format(['3 feet', '7 inches']); // "3 feet 7 inches"
スタイルオプション
- long:完全な接続詞("Apple, Banana, and Cherry")
- short:可能な場合は省略形
- narrow:最小限の区切り
2項目のリスト
new Intl.ListFormat('en', { type: 'conjunction' })
.format(['Salt', 'Pepper']); // "Salt and Pepper"
2項目リストは3項目以上のリストとは異なるフォーマットルールを持つことがよくあります(例:英語では「and」の前にカンマなし)。
ユースケース
リストフォーマットは、UIメッセージ(「カートの商品:シャツ、パンツ、靴」)、フォームバリデーション(「名前、メール、パスワードを入力してください」)、通知テキスト(「JohnとJaneと他3人があなたの投稿にいいねしました」)に使われます。Intl.ListFormatがなければ、末尾の接続詞を処理するカスタムの結合ロジックを書く必要があり、これは言語間で大きく異なります。