Trimming Whitespace from a String
Problem
You want to trim whitespace from a string.
Solution
Use JavaScript’s Regular Expression support to replace whitespace.
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:
Discussion
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:
Syntax Sugar
You can add some Ruby-like syntax sugar with the following shortcuts:
For an interesting discussion and benchmarks of JavaScript trim
performance, see this blog post by Steve Levithan.