views:

84

answers:

3

Okay I have a simple Javascript problem, and I hope some of you are eager to help me. I realize it's not very difficult but I've been working whole day and just can't get my head around it.

Here it goes: I have a sentence in a Textfield form and I need to reprint the content of a sentence but WITHOUT spaces.

For example: "My name is Slavisha" The result: "MynameisSlavisha"

Thank you

+10  A: 

You can replace all whitespace characters:

var str = "My name is Slavisha" ;
str = str.replace(/\s+/g, ""); // "MynameisSlavisha"

The /\s+/g regex will match any whitespace character, the g flag is necessary to replace all the occurrences on your string.

Also, as you can see, we need to reassign the str variable because Strings are immutable -they can't really change-.

CMS
thanks, this really helped me a lot
SlavishaZero
@SlavishaZero: the way you thank people here is by picking their answer. If CMS' answer helped you the most, pick it.
Nathan Hughes
+1  A: 

Another way to do it:

var str = 'My name is Slavisha'.split(' ').join('');
Nathan Hughes