[Javascript] trim function (regex)

Paul Novitski paul at novitskisoftware.com
Wed May 5 12:22:21 CDT 2004


At 09:56 AM 5/5/2004, Shawn Milo wrote:
...
>I wrote this in response to a newsgroup posting on comp.lang.javascript about
>a trim() function, like that in many other languages.
...
>          testString = testString.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2');


Good one, Shawn.  I had been doing the same thing with two shorter 
statements, e.g.:

         // delete leading, then trailing, white-space
         testString = testString.replace(/^\s+/, '');
         testString = testString.replace(/\s+$/, '');

...and am glad to see the one-line solution.

Paul


At 09:56 AM 5/5/2004, you wrote:
>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