How To Add Trim Functionality To Javascript String

By Angsuman Chakraborty, Gaea News Network
Sunday, August 12, 2007

Trim is a useful function available in languages like Java & PHP which removes the leading and traling whitespace(s) from a String. Unfortunately Javascript doesn’t natively provide trim functionality to the String object. Fortunately there is a simple solution. Place the following code near the top of your Javascript file (or inline script) to add trim() functionality to all String objects.


String prototype.trim = function() {
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};

This underlines one of the beauty (or beast depending on who you ask) of Javascript - the ability to add functionality to an existing class, even native classes like String, by accessing its prototype.

Now you can use trim() on any String in your code.

Filed under: Javascript, Programming, Web, Web 2.0
Discussion

Pradee[
May 11, 2009: 9:01 am

Modified it to make it work correctly….

String.prototype.trim = function() {
a = this.replace(/^[ \t]+|[ \t]+$/, ”);
return a.replace(/^[ \t]+|[ \t]+$/, ”);
};
var str=’ this is sample ! ‘;
alert(str.length);
alert(’trimmed !’);
alert(str.trim().length);


T.R.Harihara Sudhan
December 27, 2007: 11:18 pm

Sir,

I am striking with trim() option in Java script

I have a one string,

A = “E:\ram\Collections\t1.jpeg”

I need,

ans = “E:\ram\Collections\” only

Please kindly help me. I can use the trim function but it not use.

Thanks & Regards
T.R.Harihara sudhan


aji
September 16, 2007: 11:50 pm

Hi Sir,

The topic is very useful.But in this form it will not work.We have to put dot(.) after String instead of space.
String.prototype.trim = function() {
a = this.replace(/^s+/, ”);
return a.replace(/s+$/, ”);
};

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :