Go to home page mail me! RSS Feed

Replace all spaces using JavaScript.

Thursday, December 18, 2008 1:37 PM

Alright, so for the .NET developers, if you don't already know the .Replace JavaScript function does not work like the String.Replace function in .NET, in .NET, it replaces all occurrences while in JavaScript it only replaces the first instance.

 

"H e l l o W o r l d".replace(' ','');

 

will return "He l l o W o r l d" - notice the rest of the spaces weren't removed.

 

The easiest solution to the problem, assuming you want to replace all spaces in the string is to use regular expression.

 

"H e l l o W o r l d".replace(/\s/g,'');

The above will or should return "HelloWorld" with no spaces in the string.

Your Comments.

  • # re: Replace all spaces using JavaScript.

    Gravatarwowwwwww... it works... m soo happy, was trying this for sooo long... thanks a tonn.. :)

    Left by poo at 7/8/2009 5:32 AM
  • # re: Replace all spaces using JavaScript.

    GravatarIs there anyway you can reverse it? as in, seperate a string with a space?

    Left by Carly at 9/17/2009 12:07 PM

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 1 and 4 and type the answer here:

Preview Your Comment.

 
Next entries »