[Javascript] trim function (regex)

Shawn Milo milo at linuxmail.org
Wed May 5 11:56:13 CDT 2004


I'm sending this because I wanted any opinions, and because the list is slow this week.
I miss the conversation.  Also, in includes a pretty simple regex example.

I wrote this in response to a newsgroup posting on comp.lang.javascript about
a trim() function, like that in many other languages.

Comments/Corrections/Criticism welcome
Code written, commented, and tested by me.  The stardard warranty applies (none).

Shawn


      <script type="text/javascript">


         var testString = '  there are leading and trailing spaces (and tabs)       ';

         alert('\'' + testString + '\'');

         //regex explanation:
         //regex is in forward slashes:  //
         // syntax  string = string.replace(/pattern/, 'replace with this');

         //    ^        = beginning of line
         //    (\s+)?   = one or more characters of whitespace, optional
         //    (.*\S)   = any characters, with the last one not being whitespace
         //    (\s+)?   = one or more characters of whitespace, optional
         //    $        = end of line
         //    $2       = what was in the 2nd set of parenthesis

         testString = testString.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2');

         alert('\'' + testString + '\'');

      </script>





More information about the Javascript mailing list