2

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

Slavisa Perisic
  • 1,110
  • 3
  • 18
  • 32
  • possible duplicate of [Javascript to remove spaces from a textbox value](http://stackoverflow.com/questions/3960701/javascript-to-remove-spaces-from-a-textbox-value) – kennytm Oct 26 '10 at 20:16
  • http://www.w3schools.com/jsref/jsref_replace.asp – mcix Oct 26 '10 at 20:11

2 Answers2

11

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-.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 2
    @SlavishaZero: the way you thank people here is by picking their answer. If CMS' answer helped you the most, pick it. – Nathan Hughes Oct 26 '10 at 20:43
  • Could you elaborate on the difference between `.replace(/\s+/g, "")` and `.replace(/\s/g, "")`. They both seem to do the same thing. If so, then which is preferred (as in faster, etc.)? – Šime Vidas May 11 '11 at 11:15
1

Another way to do it:

var str = 'My name is Slavisha'.split(' ').join('');
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276