RegEx to remove spaces

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dante

    RegEx to remove spaces

    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(sp acefix,"");

    Thanks so much, Dante.
  • Brian Kerrick Nickel

    #2
    Re: RegEx to remove spaces

    \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.prototyp e.stripSpaces = function( ){ return this.replace( /\s/g, "" ); };

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

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

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

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

    Whatever thou prefereth.

    ..Brian

    Comment

    • Dante

      #3
      Re: RegEx to remove spaces

      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.

      Comment

      • Thomas 'PointedEars' Lahn

        #4
        Re: RegEx to remove spaces

        Dante wrote:
        [color=blue]
        > IE5 has trouble with \s. Oh well.[/color]

        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:docu ment.write(" bl blubb".replace(/\s/g, "") +
        "<br>\n"); document.write( navigator.userA gent)
        [color=blue]
        > Also I was wondering how I can write a regex that matches only words
        > and numbers, not spaces.
        >
        > I was thinking something with [:alpha:].[/color]

        /\w/g

        Get informed about the RegExp object:
        <http://devedge.netscap e.com/library/manuals/2000/javascript/1.5/reference/regexp.html#119 3136>


        PointedEars

        Comment

        Working...