Wednesday, June 15, 2011

Trim String Using Javascript

Javascript Trim Member Functions

Use the code below to make trim a method of all Strings. These are useful to place in a global Javascript file included by 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+$/,"");
}
 

Javascript Trim Stand-Alone Functions

If you prefer not to modify the string prototype, then you can use the stand-alone functions below.
function trim(stringToTrim) { return stringToTrim.replace(/^\s+|\s+$/g,""); } function ltrim(stringToTrim) { return stringToTrim.replace(/^\s+/,""); } function rtrim(stringToTrim) { return stringToTrim.replace(/\s+$/,""); }

Compatibility

The functions above use regular expressions, which are compatible with Javascript 1.2+ or JScript 3.0+. All modern browsers will support this. If you require functions for older versions of Javascript back to version 1.0, try the functions below adapted from the Javascript FAQ 4.16. These 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);
}

 

No comments:

Post a Comment