if you are not using a javascript framework and you want to trim whitespace from a text you can use the following function. And keep in mind this is very efficient rather than using for loops and searching for spaces.
//this is the function
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, "");
}
//usage:
var sampleText = " text to trim ";
var trimmedText = sampleText.trim();
//output will be:
"text to trim"