How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?
Flagrant Badassery has 11 different trims with benchmark information:
http://blog.stevenlevithan.com/archives/faster-trim-javascript
Non-surprisingly regexp-based are slower than traditional loop.
Here is my personal one. This code is old! I wrote it for JavaScript1.1 and Netscape 3 and it has been only slightly updated since. (Original used String.charAt)
/**
* Trim string. Actually trims all control characters.
* Ignores fancy Unicode spaces. Forces to string.
*/
function trim(str) {
str = str.toString();
var begin = 0;
var end = str.length - 1;
while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
while (end > begin && str.charCodeAt(end) < 33) { --end; }
return str.substr(begin, end - begin + 1);
}