[Javascript] trim function (regex)

Shawn Milo milo at linuxmail.org
Wed May 5 12:52:18 CDT 2004


----- Original Message -----
From: Paul Novitski <paul at novitskisoftware.com>
Date: Wed, 05 May 2004 10:22:21 -0700
To: "[JavaScript List]" <javascript at LaTech.edu>
Subject: Re: [Javascript] trim function (regex)

> 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

Thanks.  When I started writing it, I got stuck and had to do
a two liner.  I realized that the greedy matching was swallowing
up the spaces, and that '\S' after the '.*' was the solution.

Shawn




More information about the Javascript mailing list