javascript string ordinal

javascript string ordinal
Okay… you’re lucky I like figuring stuff out.
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>
I should mention those are abbreviated ordinals, not full ones. “21st” versus “twenty-‌first,” for example. More fun here: Custom and extended object classes for JavaScript.
[close] Permanent link · http://querylog.com/q/javascript+string+ordinal

Suggested HTML for linking:
Link preview: javascript string ordinal
27 June 2005 · Internet & computing
The page found by the original query:
Code snippets in Perl and JavaScript
Browse by the page—15 Q&R each
« previous | more »