How To Add Trim Functionality To Javascript String
By Angsuman Chakraborty, Gaea News NetworkSunday, 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.
|
May 11, 2009: 9:01 am
Modified it to make it work correctly…. String.prototype.trim = function() { |
|
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 |
|
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. |
Pradee[