String.Trim() in Javascript

Date September 1, 2009

Trim is a useful String function available in languages like Visual Basic, Java & PHP which removes all leading and traling whitespaces from a String. Unfortunately Javascript does not provide Trim functionality to the String object. But there is solution using Regular Expression. Use following code in top of your Javascript file. Following code will add trim() functionality to String objects.


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

First line in code will remove leading spaces from the String and second line code will remove trailing spaces from the String.

Happy Coding

Most Commented Posts

Tags: ,

PoorFairInterestingGoodExcellent (1 votes, average: 4.00 out of 5)
Loading ... Loading ...

Leave a Reply


Most Rated Posts

Subscribe to Technology Tips

Subscribe to Saqib-Ansari via RSS

Or, subscribe via email: