RegEx to remove spaces

D

Dante

I need a regular expression to remove all spaces from a string.
The best I could do was this:
var spacefix = / /gi;
var out = data.replace(spacefix,"");

Thanks so much, Dante.
 
B

Brian Kerrick Nickel

\s strips spaces, tabs, and line break characters. You can do /[ \t]/g if
you just want to kill nonbreaking spaces.

The easiest thing you could do would probably be:

String.prototype.stripSpaces = function( ){ return this.replace( /\s/g, "" ); };

So "H e l l o W o r l d".stripSpaces( ); would behave similarly to
..toUppercase.

For the sake of sake, this is an equally viable function:

String.prototype.strip = function( exp ){ return this.replace(exp?exp:/\s/g,""); };

With this, "H e l l o".strip(); would render "Hello", and "Hello".strip(
/[o]/ ); would render "Hell".

Whatever thou prefereth.

..Brian
 
D

Dante

IE5 has trouble with \s. Oh well.

Also I was wondering how I can write a regex that matches only words
and numbers, not spaces.

I was thinking something with [:alpha:].

Brian, you will receive credit for the Word Counter Script I am
fixing.
 
T

Thomas 'PointedEars' Lahn

Dante said:
IE5 has trouble with \s. Oh well.

Mine have not.

Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0; Q312461)
Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; Q312461)

Testcase:

javascript:document.write(" bl blubb".replace(/\s/g, "") +
Also I was wondering how I can write a regex that matches only words
and numbers, not spaces.

I was thinking something with [:alpha:].

/\w/g

Get informed about the RegExp object:
<http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/regexp.html#1193136>


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top