Intl.PluralRules.selectRange Labels Ranges

Resolve the grammatical plural form of a numeric span with Intl.PluralRules.selectRange across locales instead of guessing from the upper bound alone.

JavascriptForm Validation

Code

javascriptsnippet
16 lines
const enRules = new Intl.PluralRules('en-US');
const frRules = new Intl.PluralRules('fr-FR');

function formatRangeLabel(rules, start, end, labels) {
  const category = rules.selectRange(start, end);
  return `${start}-${end} ${labels[category] ?? labels.other} (${category})`;
}

const enLabels = { one: 'item', other: 'items' };
const frLabels = { one: 'article', other: 'articles' };

// In English 0-1 selects 'other', whereas in French 0-1 selects 'one'
console.log('en 0..1:', formatRangeLabel(enRules, 0, 1, enLabels));
console.log('en 1..5:', formatRangeLabel(enRules, 1, 5, enLabels));
console.log('fr 0..1:', formatRangeLabel(frRules, 0, 1, frLabels));
console.log('fr 1..5:', formatRangeLabel(frRules, 1, 5, frLabels));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

en 0..1: 0-1 items (other)
en 1..5: 1-5 items (other)
fr 0..1: 0-1 article (one)
fr 1..5: 1-5 articles (other)

Code mechanics — Intl.PluralRules.selectRange Labels Ranges

Reading from top to bottom highlights function formatRangeLabel, doing all the work.

Watch out for

  • No third-party code is loaded at any point while this runs.

Applying it

Entry signature: function formatRangeLabel(rules, start, end, labels)

Execution prints annotated markers — en 0..1:, en 1..5:, fr 0..1: — when the file runs.

Statements that matter

return `${start}-${end} ${labels[category] ?? labels.other} (${category})`;
const enRules = new Intl.PluralRules('en-US');
const frRules = new Intl.PluralRules('fr-FR');

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `formatRangeLabel` at load time.