Javascript Number ordinalize()

Description

Javascript Number ordinalize()


// ordinalize returns the ordinal string corresponding to integer:
////from   w ww  .  j ava 2s .co m
//     (1).ordinalize()    // => '1st'
//     (2).ordinalize()    // => '2nd'
//     (53).ordinalize()   // => '53rd'
//     (2009).ordinalize() // => '2009th'
//     (-134).ordinalize() // => '-134th'
Number.prototype.ordinalize = function() {
    var abs = Math.abs(this);
    
    if (abs % 100 >= 11 && abs % 100 <= 13) {
        return this + 'th';
    }
    
    abs = abs % 10;
    if (abs === 1) { return this + 'st'; }
    if (abs === 2) { return this + 'nd'; }
    if (abs === 3) { return this + 'rd'; }
    
    return this + 'th';
};

// Alias of to_s.
Number.prototype.toParam = Number.prototype.toString;

Number.prototype.toQuery = function(key) {
 return escape(key.toParam()) + "=" + escape(this.toParam());
};



PreviousNext

Related