0

Add ordinal suffix to a number

Function JavaScript 1 revisions 62 6 months ago 6 months ago
function getOrdinal(n) {
  const s = ['th', 'st', 'nd', 'rd'];
  const v = n % 100;
  return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
getOrdinal(5);  // 5th
getOrdinal(2);  // 2nd
getOrdinal(11); // 11th