Skip to content

Instantly share code, notes, and snippets.

@fredericmarx
Created February 29, 2020 19:38
Show Gist options
  • Save fredericmarx/effb674d11b5148bf7b79005e377e159 to your computer and use it in GitHub Desktop.
Save fredericmarx/effb674d11b5148bf7b79005e377e159 to your computer and use it in GitHub Desktop.
Get ordinal numbers in JavaScript
const getOrdinalNumber = number => {
const ordinalNumbers = [
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eigth",
"ninth",
"tenth",
"eleventh",
"twelfth"
];
if (ordinalNumbers[number - 1]) return ordinalNumbers[number - 1];
if (number.toString().slice(-1) === "1") return `${number}st`;
if (number.toString().slice(-1) === "2") return `${number}nd`;
if (number.toString().slice(-1) === "3") return `${number}rd`;
return `${number}th`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment