Handy Collection of JavaScript Prototypes

Here is a handy collection of JavaScript prototypes compiled by James Haley, I personally found these quite useful and thus I am sharing them. These are pretty much self explanatory snippets and perform some regular tasks.

Array Remove – By John Resig (MIT Licensed)

Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

Trim spaces

String.prototype.trim = String.prototype.trim || function() { return this.replace(/^\s+|\s+$/,""); }

Remove last full stop prototype

String.prototype.trimFullStops = function() { return this.replace(/^\.+|\.+$/,""); }

New line remove prototype

String.prototype.replaceNewLine = function() { return this.replace(/(\r\n|\r|\n)/g, ""); }

Replace breaks remove prototype

String.prototype.replaceBreaks = function() { return this.replace(/<br \/>|<br\/>/g, "\n"); }

String Trim to length or first Stop(.)

String.prototype.short = function(nLen) {
  var nFSPos = this.indexOf('.');
  return (this.length > nLen) ? ((nFSPos > -1) && (nFSPos < nLen + 1) && (nFSPos > 3)) ? this.split('.')[0].trim() + '…' : this.substring(0, nLen).trim() + '…' : this;
};

Encode for URL transport

String.prototype.encode = function() { return (this.length>0)?encodeURIComponent(this):this; };

Replace JS quotes

String.prototype.replaceQuotes = function() { return this.replace(/"/g,"\\\""); }

HTML remove tags prototype

String.prototype.stripTags = function() { return this.replace(/<\S[^>]*>/g, ""); }

Fix Numeric

String.prototype.tidyNumeric = function() { return Math.abs(this.replace(/[^0-9.]/ig,'').trimFullStops()); };

Tidy Decimal

Number.prototype.tidyDecimal = function(n) { return Math.abs(this.toFixed(n)); }

Convert to EM (base size 12px)

Number.prototype.toEm = function() { return (this/12).tidyDecimal(3); }

Right and Left cut

String.prototype.left = function(n) { return this.substr(0,n); }; String.prototype.right = function(n) { return this.substr((this.length-n),this.length); };

Convert date object into friendly string

Date.prototype.toClean = function() {
   if (this !== null) {
       var vDay = ((this.getDate()) < 10) ? '0' + (this.getDate()) : (this.getDate()),
           oMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
           vMonth = oMonths[this.getMonth()],
           vYear = this.getFullYear().toString().right(2);
       return vDay + ' ' + vMonth + ' \'' + vYear;
   } else {
       return '[Invalid Date]';
   }

}

Convert date object into SQL supported

Date.prototype.toSQL = function() {
    var vDay = ((this.getDate()) < 10) ? '0' + (this.getDate()) : (this.getDate()),
        nMonth = (this.getMonth() + 1),
        vMonth = (nMonth < 10) ? '0' + nMonth : nMonth,
        vYear = this.getFullYear().toString(),
        vHours = ((this.getHours()) < 10) ? '0' + (this.getHours()) : (this.getHours()),
        vMinutes = ((this.getMinutes()) < 10) ? '0' + (this.getMinutes()) : (this.getMinutes()),
        vSeconds = ((this.getSeconds()) < 10) ? '0' + (this.getSeconds()) : (this.getSeconds());
    return vDay + '/' + vMonth + '/' + vYear + ' ' + vHours + ':' + vMinutes + ':' + vSeconds;
}

Remove all punctuation

String.prototype.clearPunc=function(){ return this.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").replace(/\s{2,}/g," "); }

Highlight words by passed in value

String.prototype.highlight = function(vWords) {
    var oWords = vWords.clearPunc().stripTags().split(' '),
        vNewPhrase = this;
    oWords.each(function(o) {
        vNewPhrase = vNewPhrase.replace(new RegExp("(" + o + ")", "ig"), '<span class="highlight">$1</span>');
    });
    return vNewPhrase;
}
  • Daniel Tate

    It's very bad practice to inherit from Global Javascript Objects the Javascript API is subject to change and shouldn't be relied on like this.

    The best way to implement these would be to create a helper object or your own object with methods that complete these tasks.

    The problem with this is that in the future (highlight) might be a native method of the Javascript String Object. Now you have a conflict and you are not sure why your program is breaking.

    Is it because your code is wrong or because your program is reacting strangely to the Browsers implementation of the Native method?