Slavisa Perisic
Slavisa Perisic

Reputation: 1110

Deleting empty spaces in a string

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

Upvotes: 2

Views: 220

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96394

Another way to do it:

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

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827496

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

Upvotes: 11

Related Questions