The simple one-line solution
I recently searched for a JavaScript that could dynamically calculate an English language number suffix i.e. “st”, “nd”, “rd” or “th”; but was astounded by how many of the available scripts either returned incorrect results or, when a correct result was returned, used an abundance of code to calculate the suffix.
So, for anyone searching for a similar script, here’s a quick function that should do the trick:
function daySuffix(d) {
d = String(d);
return d.substr(-(Math.min(d.length, 2))) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 ? "th" : ["th", "st", "nd", "rd", "th"][Math.min(Number(d)%10, 4)];
}
Just pass a number to the function and it will return the correct English language suffix e.g. calling daySuffix(113) will return “th”, calling daySuffix(3) will return “rd”.
A demo of the function in action is now available.

Previous Comments ~
hey geek !! how is it doing ????
please be free on the 9th of september. It’s my 30 and Id like to see you both (swiming pool, Dj’s etc)
(by the way, I do not understand function daySuffix(d) {
return d.substr(-(Math.min(d.length, 2))) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 ? “th” : [“st”, “nd”, “rd”,
“th”][Math.min(d%10, 4)-1];
@ Ice: Hey man, good to hear from you… of course I’ll be free on the 9th (as long as it’s not you on the turntables). As for being a “geek”... erm… I most probably am.
P.S. Couldn’t you just have sent me an email?
P.P.S. You English language skills are getting worse with each comment.
See ya soon,
Brian.
Ummm – Hi Brian.
I’m returning “rd” for 113 which I don’t think is quite correct.
Also, you’ve left of the closing bracket of the function…
Cheers,
Richard :o)
@ Richard: Hi Richard, well spotted… I forgot to cast the input to a String. The following seems to work:
function daySuffix(d) {
d = String(d); return d.substr(-(Math.min(d.length, 2))) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 ? “th” : [“st”, “nd”, “rd”, “th”][Math.min(d%10, 4)-1];}
alert(daySuffix(113));
alert(daySuffix(“113”));
Thanks for the comment.
Regards,
Brian.
Your example returns “undefined” for numbers ending in zero that are larger than 20 (i.e., 30, 40, 50, etc.). Oddly, when I create an array of suffixes using an array constructor, it works fine.
function getSuffix(d) {
d = String(d);
var suffix = new Array();
suffix
1] = “th”;suffix0 = “st”;
suffix1 = “nd”;
suffix2 = “rd”;
suffix3 = “th”;
var result = d.substr((Math.min(d.length, 2))) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 ? “th” : suffix[Math.min(d%10, 4)-1];
return result;
}
Sorry, the array in that last comment should have looked thusly:
var suffix = new Array();
suffix[-1] = “th”;
suffix0 = “st”;
suffix1 = “nd”;
suffix2 = “rd”;
suffix3 = “th”;
Mark
@ Mark: This is getting embarrasing now… I’ve posted an update that fix’s the problem.
Thanks for the warning!
Regards,
Brian.
Comments are currently closed for this article but feel free to email me with your input - I’d love to hear it.