JavaScript Trim() function
Trim(), is one function that we all use almost every day in most languages, whether it’s a core function of the language you’re using or a member (or prototype in JavaScript) function of the String object itself (as in C#), it’s invaluable for developers.
Unfortunately JavaScript doesn’t have this sort of thing built in, so here’s how to implement your own trim() functions (as well as ltrim() and rtrim()) in various ways depending on the level of backward compatibility you require.
trim() member functions
Use the code below to make trim a method of all Strings. Ordinarily you would place this code into a global JavaScript file that would be included in all your pages.
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}
Examples using trim(), ltrim(), and rtrim() prototyped methods
var testString = " hello world ";
alert("#"+ testString.trim() +"#");
alert("#"+ testString.ltrim() +"#");
alert("#"+ testString.rtrim() +"#");
standalone JavaScript functions
If you’d prefer to use regular functions to return trimmed strings rather than modifying the String object using prototyping, then try the following code:
function trim(value) {
return value.replace(/^\s+|\s+$/g,"");
}
function ltrim(value) {
return value.replace(/^\s+/,"");
}
function rtrim(value) {
return value.replace(/\s+$/,"");
}
Examples using trim(), ltrim(), and rtrim() functions
var testString = " hello world ";
alert("#"+ trim(testString) +"#");
alert("#"+ ltrim(testString) +"#");
alert("#"+ rtrim(testString) +"#");
Compatibility
The above functions require JavaScript 1.2+ and JScript 3.0+ as they are using Regular Expressions to work their magic. This pretty much covers all modern browsers (v4 and above of IE and opera, and all versions of Firefox).
If you require functions that will be compatible with very old browsers only supporting JavaScript 1.0 or there about, try using the following set of functions. These functions strip the following standard whitespace characters: space, tab, line feed, carriage return, and form feed. The IsWhitespace function checks if a character is whitespace.
function ltrim(str) {
for(var k = 0;
k < str.length && isWhitespace(str.charAt(k));
k++);
return str.substring(k, str.length);
}
function rtrim(str) {
for(var j=str.length-1;
j>=0 && isWhitespace(str.charAt(j));
j--);
return str.substring(0,j+1);
}
function trim(str) {
return ltrim(rtrim(str));
}
function isWhitespace(charToCheck) {
var whitespaceChars = " \t\n\r\f";
return (whitespaceChars.indexOf(charToCheck) != -1);
}



