Remove side space in string

August 5, 2010 | In: javascript, php, web development

Javascript Trim 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)+"*");