Ben Nadel has a nice post on trimming strings with javascript using regular expressions.
Note that the reg exp white space character ‘\s’ is used to match:
- space
- tab
- horizontal tab
- vertical tab
- line break
Sample code below:
Update 25th March 2007:
A basic breakdown:
- /…/
- Regular expressions in javascript are delimited with forward slashes
- ^
- Outside the usual square brackets, the caret means look only at the beginning of the target string
- |
- Alternatation, meaning finding the left hand OR right have values
- \s*
- Denotes 0 to many white space characters
- $
- Means look only at the end of the target string
- g
- Makes the search global; finding all matches, not just the first match
Of course all we’re doing is replacing left and right white space with an empty string (”").
Leave a Reply