Trimming Whitespace from a String
You want to trim whitespace from a string.
To trim leading and trailing whitespace, use the following:
To trim only leading whitespace, use the following:
To trim only trailing whitespace, use the following:
Opera, Firefox and Chrome all have a native string prototype
trim method, and the other browsers could add one as well. For this particular method, I would use the built-in method where possible, otherwise create a polyfill:
You can add some Ruby-like syntax sugar with the following shortcuts:
trim performance, see this blog post by Steve Levithan.