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 “;

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 “;




Hope this helps.

Feel free to leave a reply here...

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

You are commenting using your 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: