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.