OpenNTF.org - Trim
My Links (Not logged in)
Code Bin Search
 
Hosted by Prominic.NET
Rate This Code
5 - brilliant stuff
4 - very nice
3 - average
2 - needs work
1 - bad
   OpenNTF Code Bin
About This Code
Brief Description:
Trim 
Rating:
Not Rated Yet 
Contributor:
Jani Krunniniva 
Category:
Javascript 
Type:
String functions 
Notes Version:
R4.x, R5.x, R6.x 
Last Modified:
17 Oct 2002 
OpenNTF Disclaimer

All of the program code and information presented in the OpenNTF.org Code Bin are provided "as-is", and should be used at your own risk. OpenNTF.org make no express or implied warranty about anything in the Code Bin, and OpenNTF.org will not be responsible or liable for any damage caused by the use or misuse of anything from this site. OpenNTF.org makes no guarantees about anything. Please thoroughly test all of the knowledge and code you find here before you attempt to use them in your production environment.

Code / Description
//...a function to remove leading blanks, which could cause problems...

function trim(strIn) {
sl = strIn.length;
if ( strIn.substring(sl-1, sl) == " "){
strOut = strIn.substring(0,sl-1) }
else strOut = strIn;
for (var t = 0; t < strIn.length; t++ ) {
if ( strIn.substring( t, t+1 ) != " " ) {
return (strOut);
}
else {
strOut = strIn.substring( t+1, strIn.length);
}
}
alert(strOut)
return (strOut)
}

Usage / Example
 Comments
Posted by Florin G Jurcovici on 12/28/2002 12:47:28 PMRe:
Don't mean to be rude, but the implementation is inefficient. How about these? function LTrim(strValue) { var int1; for (int1 = 0; strValue.charAt(int1++) == " "; ); return strValue.substring(int1, strValue.length); } function RTrim(strValue) { var int1; for (int1 = strValue.length - 1; strValue.charAt(int1--) == " "; ); return strValue.substring(0, int1 + 2); // why 2: 1 is for ++ and 1 is because of // (last char pos) + 1; } function Trim(strValue) { var int1; var int2; for (int1 = 0; (strValue.charAt(int1) == " ") && (int1 < strValue.length); int1++); for (int2 = strValue.length - 1; (strValue.charAt(int2) == " ") && (int2 > int1); int2--); return strValue.substring(int1, int2 + 1); } They seem shorter and more eficient to me, and even if it's JS, if you have a few dozens times to them in one operation, speed becomes an issue. Speed is also the reason why Trim is not a successive call to Ltrim and RTrim. Indeed, a full trim (mimicking @Formula's @Trim would need another implementation, more alike with the function in the code snippet.
Posted by Emanuele Sandri on 08/08/2003 06:38:36 PMBetter implementation
function Trim( text ) {
var x=text;
x=x.replace(/^\s*(.*)/, "$1");
x=x.replace(/(.*?)\s*$/, "$1");
return x;
}
 Add your comment!