After looking at someone else's implementation, I improved mine and created the smallest version that I could think of with the first parameter being the number and the second being the boolean indicating whether or not to show the number. I also used a closure in order to prevent the array from being recreated every time the function ran (this improves the speed):
Code:
(function(b){Number.getOrdinalFor=function(a,c){return(c?a:"")+(b[((a=Math.abs(a%100))-20)%10]||b[a]||"th")}})([,"st","nd","rd"]);
This function is only 130 characters long and will work for all integers. I also came up with a pretty cool example of how to use this for a string full of numbers:
Code:
var str = "1, 2, 3, 4.5, 6, and 7 are all numbers.";
alert(str.replace(/(\d+)/g, Number.getOrdinalFor));
I wrote a blog post about this function definition here:
http://gotochriswest.com/blog/2012/0...getordinalfor/
Let me know if you can write the equivalent function in an even shorter way while also making sure that something like an array doesn't have to be generated every time the function is called. That last requirement is what makes my function a little longer than it seems it needs to be.