Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
Discussion GroupsGeneralPHPASPPerlColdFusionFlashHTML, CSS, ScriptsBrowsers

Webmaster Forum / HTML, CSS, Scripts / JavaScript / September 2005



Tip: Looking for answers? Try searching our database.

How-to: JavaScript trim() and normalize-space() functions

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Alex Vassiliev - 29 Sep 2005 02:28 GMT
Hi all.

Just wanted to share two handy RegEx expressions to strips leading and
trailing white-space from a string, and to replace all repeated spaces,
newlines and tabs with a single space.

* JavaScript example:

    String.prototype.trim = function() {
        // Strip leading and trailing white-space
        return this.replace(/^\s*|\s*$/g, "");
    }

    String.prototype.normalize_space = function() {
        // Replace repeated spaces, newlines and tabs with a single space
        return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
    }

    " one \t two   three \n ".trim();  // --> "one \t two   three"
    " one \t two   three \n ".normalize_space();  // --> "one two three"

Enjoy,
Alex Vassiliev  (New Zealand)
commercial - 29 Sep 2005 09:08 GMT
you will not even get there on an OS handling basis
-----------

you are a lonely motherf*er

> Hi all.
>
[quoted text clipped - 19 lines]
> Enjoy,
> Alex Vassiliev  (New Zealand)
Michael Winter - 29 Sep 2005 12:50 GMT
[Corrected top-post]

[snip]

>> String.prototype.trim = function() {
>> // Strip leading and trailing white-space
>> return this.replace(/^\s*|\s*$/g, "");
>> }

Incidentally, this already exists in the group FAQ
(<URL:http://www.jibbering.com/faq/#FAQ4_16>).

>> String.prototype.normalize_space = function() {
>> // Replace repeated spaces, newlines and tabs with a single space
>> return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
>> }

Useful as they are, lookahead assertions aren't available in all
browsers. Unless you're happy compromising execution by raising syntax
errors, they should be avoided:

  String.prototype.normalise = function() {
    return this.replace(/^\s+|\s+$/g, '').replace(/\s{2,}/g, ' ');
  };

One thing that needs consideration is behaviour with mixed whitespace.
Your regular expression saves the last whitespace character in a
sequence. So, an earlier character could have been a new line, but might
be replaced by a space. Conversely, the sequence could have been all
spaces with the exception of a final new line, and it's that character
that is saved.

By comparison, the alternative above would always replace a whitespace
sequence with a single space.

[snip]

> you will not even get there on an OS handling basis

If you do insist on posting, will you at least make sense. And don't
top-post.

> you are a lonely motherf*er

However, if you're going to behave like that, could you refrain from
posting at all.

Mike

Signature

Michael Winter
Prefix subject with [News] before replying by e-mail.

Alex Vassiliev - 29 Sep 2005 22:00 GMT
>One thing that needs consideration is behaviour with mixed whitespace.
>Your regular expression saves the last whitespace character in a
>sequence. So, an earlier character could have been a new line, but might
>be replaced by a space. Conversely, the sequence could have been all
>spaces with the exception of a final new line, and it's that character
>that is saved.

Good one!  I haven't thought about that... It is definitely a bug.
Thank you Michael
Evertjan. - 29 Sep 2005 09:22 GMT
Alex Vassiliev wrote on 29 sep 2005 in comp.lang.javascript:

>      String.prototype.trim = function() {
>           // Strip leading and trailing white-space
>           return this.replace(/^\s*|\s*$/g, "");
>     }

Nice one, Alex.

To have them all [the recurses are a variation]:

<script type='text/javascript'>

String.prototype.trim = function(x) {
 if (x=='left')
   return this.replace(/^\s*/,'');
 if (x=='right')
   return this.replace(/\s*$/,'');
 if (x=='normalize')
   return this.replace(/\s{2,}/g,' ').trim();

 return this.trim('left').trim('right');
}

test = ' \n   blah \n blah \n  '
alert('x'+test+'x')
alert('x'+test.trim('left')+'x')
alert('x'+test.trim('right')+'x')
alert('x'+test.trim('both')+'x')
alert('x'+test.trim('normalize')+'x')
alert('x'+test.trim()+'x')

</script>

Signature

Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Dr John Stockton - 30 Sep 2005 12:42 GMT
JRS:  In article <1127957322.161964.192620@g47g2000cwa.googlegroups.com>
, dated Wed, 28 Sep 2005 18:28:42, seen in news:comp.lang.javascript,
Alex Vassiliev <alex.vassiliev@gmail.com> posted :

>       String.prototype.normalize_space = function() {
>               // Replace repeated spaces, newlines and tabs with a single
>space
>               return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
>       }

That won't work for me.

Otherwise, I might have used it in my presently-crude paragraph-packer.

I much dislike reading articles,
usually
press statements or similar, in
which the
layout is like this forced
example
(but wider).

So I added a "Pack" button to <URL:http://www.merlyn.demon.co.uk/js-
quick.htm>; its code is still crude.

Signature

© 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.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.