JRS: In article <Xn********************@194.109.133.242>, dated Tue, 1
Aug 2006 17:40:49 remote, seen in news:comp.lang.javascript, Evertjan.
<ex**************@interxnl.netposted :
>Bosconian wrote on 01 aug 2006 in comp.lang.javascript:
>I know that
str.replace(/^\s+|\s+$/g,'');
will trim a string of space, but what about removing extra spaces from
the middle?
[white space \s is more than spaces]
>Where
"hello world"
becomes
"hello world"
result = str.replace(/^\s+|\s+$/g,'').replace(/\s+/g,' ');
That compresses all multiple whitespace, including newlines. Within a
RegExp, a space is a perfectly good character, standing for itself.
{And if one wants a visible break in a RegExp (as literal or string)
ISTM that escaping a real space with a \ should (but doesn't) do it.]
Try .replace(/ +/g, ' ')
or .replace(/[ \t]+/g, ' ')
One might also want to remove residual single leading and trailing
spaces on each line.
<FAQENTRY>
ISTM that FAQ 4.16 is *technically* wrong, in that ASCII should read
UniCode.
More importantly, ISTM that it should mention that \s includes both
horizontal and vertical whitespace; the latter may sometimes be better
untrimmed.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.