Saturday, 18 April 2015

JavaScript Extensions

Most of this information is available on the net. I have compiled into a single document for easy reading.

JavaScript code is after the descriptions.


Methods available:
  • trim()
  • ltrim() -- left trim
  • rtrim () -- right trim
  • reverse() -- reverse string
  • defaultString() -- if the string is null or undefined then it is transformed into empty string
  • defaultNumber() -- if number is null or undefined then it is transformed into 0
  • endsWith(chars) -- returns true/false

 

 Extensions.js


String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, "");
};
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
};
String.prototype.reverse = function () {
    var res = "";
    for (var i = this.length; i > 0; --i) {
        res += this.charAt(i - 1);
    }
    return res;
};
String.prototype.defaultString = function () {
    var res = "";
    if (this != "undefined" && this != null)
        res = this;
    return res;
};
Number.prototype.defaultNumber = function() {
    var n = 0;
    if(this != "undefined" && this != null && this != "" && !isNaN(this))
        n = this;
    return n;
};
String.prototype.endsWith = function(s) {
    return this.length >= s.length && this.substr(this.length - s.length) == s;
};