How to automatically add suffix "st, nd, rd, th" to numbers by javascript?

Hi everyone. How to automatically add suffix “st”, “nd”, “rd”, “th” to numbers with Javascript?

For example, whenever a number is wrapped by span with an ID,
<span id="suffix">22</span> Ceremony
It will automatically render:
22th Ceremony

I tried using ::after and write a javascript myself, and looked for answer here “javascript - Add st, nd, rd and th (ordinal) suffix to a number - Stack Overflow”, but no success yet.

Thanks a lot.

Does anybody have an idea?

Thanks a lot.

Here you go! Used the code from the same Stack Overflow answer.

The first segment is for when you’re trying to convert one number (uses ID) and the second segment is for when you’re trying to convert a bunch of numbers (uses Class).

For both of them you need to have the function included beforehand.

1 Like

@ktoo was faster than me :slight_smile: still here is my solution, the idea is the same: you’d need to add a class to your spans to get it automatically updated.



<span class="suffix">21</span> Ceremony <br>
<span class="suffix">22</span> Ceremony <br>
<span class="suffix">23</span> Ceremony <br>
<span class="suffix">24</span> Ceremony <br>

ES6 JavaScript:

// 🍓 "suffixMe" function definition
function suffixMe(num) {
  // 🍋 remainder operations dealing with edge case
  const j = num % 10,
    k = num % 100;
  // 🥬 return respective suffix accordingly
  if (j == 1 && k != 11) {
    return `${num}st`;
  } else if (j == 2 && k != 12) {
    return `${num}nd`;
  } else if (j == 3 && k != 13) {
    return `${num}rd`;
  } else {
    return `${num}th`;

// 🍑 create array of numbers
const numbers = Array.from(document.getElementsByClassName("suffix"));
// 🍇 apply function definition for each number
numbers.forEach((number) => {
  const suffix = suffixMe(Number(number.textContent));
  // 🍊 override original number with its newly return suffixed number
  number.textContent = suffix;

Oh nice! I prefer yours to be honest! I’m new to JS and learned a few things reading your code! .textContent and Array.from() are new to me! Also very cool that you can name a constant in plural and then iterate through the plurality using the singular form of the constant’s name!


Thanks @ktoo and @anthonysalamin for the answers.
Clean and works well! :raised_hands: :raised_hands:

Hope other people will also find this useful.

1 Like

Indeed that forEach loop is pretty neat. I personnally use plural for array’s name and the singular for the respective single element of the array inside the forEach loop but you can use any name you want really. I just think it reads well and makes the code easier to understand.

I have a jquery option with the script on the page scripts. See my read only solution.

You will need to publish and view the published site.


1 Like

Cool jQuery solution !