Number.prototype.toOrdinal = function () {
var i = this.toString();
if ( i.match(/\D/) ) return i;
if ( i == 3 || i.match(/[^1]3$/) ) return i + 'rd';
if ( i == 2 || i.match(/[^1]2$/) ) return i + 'nd';
if ( i == 1 || i.match(/[^1]1$/) ) return i + 'st';
return i + 'th';
}
Or for snappier XHTML:
Number.prototype.toOrdinalHTML = function () {
var i = this.toString();
if ( i.match(/\D/) ) return i;
if ( i == 3 || i.match(/[^1]3$/) ) return i + '<sup>rd</sup>';
if ( i == 2 || i.match(/[^1]2$/) ) return i + '<sup>nd</sup>';
if ( i == 1 || i.match(/[^1]1$/) ) return i + '<sup>st</sup>';
return i + '<sup>th</sup>';
}
Here’s a little test script you can use to see it working.
<script type="text/javascript">
// include the above class prototype extensions here
for ( var n = 0; n < 250; n++ ) {
document.write( n.toOrdinal() + ' ' );
}
</script>