Wednesday, 29 May 2013

JavaScript - String Extensions #1 [ isEmpty(), left(), right(), contains(), repeat() ]

Often, when I am working with Strings in JavaScript, I need many common functions.
Such as the left(), right(), isEmpty(), contains(), ETC.
To make work easier, I wrote a few to appropriate extensions for String:
/****************************************
* String extensions
****************************************/
String.prototype.isEmpty = function () {
    /// 
    /// Check if string is empty
    /// 
    return (this.length === 0);
};

String.prototype.left = function (subStringLength) {
    /// 
    /// Gets left part of string
    /// 
    if (subStringLength > this.length) return this;
    return this.substring(0, subStringLength);
};

String.prototype.right = function (subStringLength) {
    /// 
    /// Gets right part of string
    /// 
    if (subStringLength > this.length) return this;
    return this.substring(this.length, this.length - subStringLength);
};

String.prototype.contains = function (subString) {
    /// 
    /// Checks if strin contains other string
    /// 
    if (this.indexOf(subString) > 0) return true;
    return false;
};

String.prototype.repeat = function (num) {
    /// 
    /// Repeates string [num]-times
    /// 
    if (isNaN(num)) return null;
    if (!(num > 0)) return "";
    return new Array(num + 1).join(this);
};