Sometimes, we want to add an ordinal suffix to a JavaScript number.
In this article, we’ll look at how to add an ordinal suffix to a JavaScript number.
Use the Intl.PluralRules Constructor
We can add the correct ordinal suffix to a JavaScript number easily with the Intl.PluralRules constructor.
For instance, we can use it by writing:
const ordinal = (number) => {
const ordinalRules = new Intl.PluralRules("en", {
type: "ordinal"
});
const suffixes = {
one: "st",
two: "nd",
few: "rd",
other: "th"
};
const suffix = suffixes[ordinalRules.select(number)];
return (number + suffix);
}
console.log(ordinal(101))
We create the ordinal function with the number parameter.
In the function, we create the ordinalRules object with the Intl.PluralRules constructor.
The first argument is 'en' which gets the rules for the English locale.
The 2nd argument is an object with type set to 'ordinal' which lets us return the ordinal rules.
Next, we create the suffixes object with the rules.
Then we call the select method with the number to return 'one' , 'two' , 'few' or 'other' .
So the suffix would be one of the property values in suffixes .
And finally, we return the number and suffix concatenated together.
Therefore the console log should log '101st' .
Conclusion
We can use the Intl.PluralRules constructor to add an ordinal suffix to a JavaScript number.