Wednesday, September 8, 2010

JavaScript Trim Functions

A JavaScript string function does not have in built string trimming functions available. Hence we found following codes when we Google it out on the net. To save your time in searching for required string trimming functions we consolidated all the information we got from the net.

The first is a definition of the seperate function ltrim, rtrim and trim. These trim the spaces to the left of the string, the right of the string and both sides respectively.

function trim(s)

{

return rtrim(ltrim(s));

}

function ltrim(s)

{

var l=0;

while(l <>

{ l++; }

return s.substring(l, s.length);

}

function rtrim(s)

{

var r=s.length -1;

while(r > 0 && s[r] == ' ')

{ r-=1; }

return s.substring(0, r+1);

}

If you are only going to use trim, you might want to use this, probably faster, defenition:

function trim(s)

{

var l=0; var r=s.length -1;

while(l <>

{ l++; }

while(r > l && s[r] == ' ')

{ r-=1; }

return s.substring(l, r+1);

}

Reference Blog: http://doc.infosnel.nl/javascript_trim.html


If you are familiar with REGEX following code will provide you more better efficiency than previous codes. This will also reduce your lines of code.

function trim(stringToTrim) {

return stringToTrim.replace(/^\s+|\s+$/g,"");

}

function ltrim(stringToTrim) {

return stringToTrim.replace(/^\s+/,"");

}

function rtrim(stringToTrim) {

return stringToTrim.replace(/\s+$/,"");

}

// example of using trim, ltrim, and rtrim

var myString = " hello my name is ";

alert("*"+trim(myString)+"*");

alert("*"+ltrim(myString)+"*");

alert("*"+rtrim(myString)+"*");

Reference Blog: http://www.somacon.com/p355.php

Always Search @ Fukat Ka Gyan: Hub For Quick Solutions

No comments:

Post a Comment