Dotnet like Trim method in JavaScript to Trim any string, char or blank spaces

We have already discussed, How to create own extension method in javascript. By using that extension methodology, we will create our own dotnet like trim method, which will able to trim blank spaces, character, string etc.

In this you will able to use the trim methods in your case as as
1. LTrim
       Trim Blank Spaces: var trimmedText = "Akash    ".LTrim();  
                  Output: Akash;
       Trim Some String: var trimmedText = "AkashSS".LTrim("S");
                Output: Akash
2. RTrim

       Trim Blank Spaces: var trimmedText = "    Akash".RTrim();  
                  Output: Akash;
       Trim Some String: var trimmedText = "SSAkash".RTrim("S");
                Output: Akash


3. Trim

       Trim Blank Spaces: var trimmedText = "     Akash    ".Trim();  
                  Output: Akash;
       Trim Some String: var trimmedText = "SSSAkashSS".Trim("S");
                Output: Akash


Code

String.prototype.RTrim = function(trimString) {
        var re;
        if (trimString==null || trimString == '') {
            re = new RegExp('\\s\\s*$');
        }
        else {
            re = new RegExp(trimString + '(' + trimString + ')*$');
        }
        return this.replace(re,'');
    }


String.prototype.LTrim = function(trimString) {
        var re;
        if (trimString == null || trimString == '') {
            re = new RegExp('^\\s\\s*');
        }
        else {
                     re = new RegExp('^' + trimString + '(' + trimString + ')*');
        }
        return this.replace(re,'');
    }
String.prototype.Trim = function(trimString){
        return this.LTrim(trimString).RTrim(trimString);
    }



No comments:

Post a Comment