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+$/,"");
}

// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");

Example

Type in the box below and you will see the trimmed output dynamically. You must enter spaces before and after the string to see a difference. All whitespace is removed, including tabs and line feeds.

Type text here:
Trim
Left Trim
Right Trim

Compatibility

The functions above use regular expressions, which are compatible with Javascript 1.2+ or JScript 3.0+. All modern (version 4+) 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);
}
posted on 2007-10-24 10:21  冷火  阅读(830)  评论(1编辑  收藏  举报