chapter31

development in a land far far away…

at the moment

History is not what happened. History is what was written down.

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:

Javascript: trimString.js

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 (”").


Related Pages

Leave a Reply