65.9K
CodeProject is changing. Read more.
Home

JavaScript string helper class

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 16, 2010

CPOL
viewsIcon

27334

Save the following code to a .js file or add to an existing one you might have:function stringHelper() { this.isNullOrEmpty = function(str) { if (null == str) return true; str = this.trim(str); return str.length == 0; } this.trim =...

Save the following code to a .js file or add to an existing one you might have:
function stringHelper() {
    this.isNullOrEmpty = function(str) {
        if (null == str) return true;
        str = this.trim(str);
        return str.length == 0;
    }
    
    this.trim = function(str, chars) {
        return this.ltrim(this.rtrim(str, chars), chars);
    }
 
    this.ltrim = function(str, chars) {
        chars = chars || "\\s";
        return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    }
    
    this.rtrim = function (str, chars) {
        chars = chars || "\\s";
        return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
    }
    this.return2br = function (str) {
        if (this.isNullOrEmpty(str)) return "";
        return str.replace(/(\r\n|\r|\n)/g, "<br />");
    }
}
var StringHelper = new stringHelper();
To use, just use the StringHelper class instance, e.g.
StringHelper.trim("    this is some text   ");