1st 2nd 3rd function js code example

Example 1: javascript add nd st th to number

function ordinal(number) {
    const english_ordinal_rules = new Intl.PluralRules("en", {
        type: "ordinal"
    });
    const suffixes = {
        one: "st",
        two: "nd",
        few: "rd",
        other: "th"
    }
    const suffix = suffixes[english_ordinal_rules.select(number)];
    return (number + suffix);
}

ordinal(3); /* output: 3rd */
ordinal(111); /* output: 111th */
ordinal(-1); /* output: -1st */

Example 2: add st nd rd th javascript

The rules are as follows:

1. st is used with numbers ending in 1 (e.g. 1st, pronounced first)
2. nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second)
3. rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third)

Note* : As an exception to the above rules, all the "teen" numbers ending with 11, 12
or 13 use -th (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred
[and] twelfth)
th is used for all other numbers (e.g. 9th, pronounced ninth).

The following JavaScript code (rewritten in Jun '14) accomplishes this:

function ordinal_suffix_of(i) {
    var j = i % 10,
        k = i % 100;
    if (j == 1 && k != 11) {
        return i + "st";
    }
    if (j == 2 && k != 12) {
        return i + "nd";
    }
    if (j == 3 && k != 13) {
        return i + "rd";
    }
    return i + "th";
}