Description
This set of Javascript functions trim or remove whitespace from the ends of strings. These functions can be stand-alone or attached as methods of the String object. They can left trim, right trim, or trim from both sides of the string. Rather than using a clumsy loop, they use simple, elegant regular expressions. The functions are granted to the public domain.
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+$/,"");
}
// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+myString.trim()+"*");
alert("*"+myString.ltrim()+"*");
alert("*"+myString.rtrim()+"*");
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+$/,"");
}
// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");