Javascript Trim, Left Trim & Right Trim Functions


Javascript string property does not have the normal trim functions like we have in any other language. And these trim functions appears play a crucial role in any code based on strings. There are two approaches i give here. One is directly creating a prototype method and other as a standalone function. You can choose the one depending on your needs.

Trim functions on the string prototype:

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()+”*”);

Trim functions as a standalone:

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)+”*”);

Hope this helps.

Feel free to leave a reply here...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: