Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

JavaScript string helper class

0.00/5 (No votes)
16 Feb 2010CPOL 27.3K  
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:

C#
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.

C#
StringHelper.trim("    this is some text   ");

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)