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
  • 31
  • 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ó
  • 769,263
  • 179
  • 909
  • 832
1

Another way to do it:

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