Trim Functions in Javascript Equivalent to PHP Functions

by Sasikumar 2014-07-10 14:32:48

We can use the following trim functions to manipulate the PHP trim functions
Javascript Trim Function:
// Trims at both end of the string
function trim(myString,trimchar) {
            if(trimchar==",") return myString.replace(/^,+|,+$/g,"");
            else if(trimchar==".") return myString.replace(/^.+|.+$/g,"");
            else return myString.replace(/^s+|s+$/g,"");
}

// Trims at left end of the string only
function ltrim(myString,trimchar) {
            if(trimchar==",") return myString.replace(/^,+/,"");
            else if(trimchar==".") return myString.replace(/^.+/,"");
            else return myString.replace(/^s+/,"");
}
        
// Trims at right end of the string only
function rtrim(myString,trimchar) {
            if(trimchar==",") return myString.replace(/,+$/,"");
            else if(trimchar==".") return myString.replace(/.+$/,"");
            else return myString.replace(/s+$/,"");
}
Example Usage:
var myTestString = "    This is my test string     ";
var myTestStringComma = ",,,,,This is my test string,,,,";
var myTestStringDot = ".....This is my test string......";

alert("SpaceTrim:{"+trim(myTestString," ")+"}"+"CommaTrim:{"+trim(myTestStringComma,",")+"}"+"DotTrim:{"+trim(myTestStringDot,".")+"}");
alert("SpaceTrim:{"+ltrim(myTestString," ")+"}"+"CommaTrim:{"+ltrim(myTestStringComma,",")+"}"+"DotTrim:{"+ltrim(myTestStringDot,".")+"}");
alert("SpaceTrim:{"+rtrim(myTestString," ")+"}"+"CommaTrim:{"+rtrim(myTestStringComma,",")+"}"+"DotTrim:{"+rtrim(myTestStringDot,".")+"}");
Syntax :
trim("String to trim", "String Remover");
ltrim("String to trim", "String Remover");
rtrim("String to trim", "String Remover");
Note: Currently "String Remover" Supports only Space( ), Comma(,) and  Dot(.)
1411
like
0
dislike
0
mail
flag

You must LOGIN to add comments