Friday, February 8, 2013

The missing Javascript prototypes.

Javascript is missing some prototypes, and so is jQuery.
The following relate to strings, and are heavily inspired by Java methods. This is what I use to trim strings and clean strings of HTML entities.
String.prototype.othertrim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
String.prototype.fulltrim=function(){
    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
};
String.prototype.replaceHtmlEntites = function() {
    var s = this;
    var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
    var translate={"nbsp":" ","amp":"&","quot":"\"","lt":"<","gt":">"};
    return(s.replace(translate_re, function(match, entity) {
        return(translate[entity]);
    }) );
};
These are for jQuery. The first is a POST method that is similar to $.getJSON. The other tells you if a tag exists. You can then do a $('#tagcheck').exists(); and it will return 0 if the tag is not present.
$.postJSON = function (url, data, callback) {
   $.post(url, data, callback, "json");
};
jQuery.fn.exists = function(){return this.length>0;}

No comments:

Post a Comment