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

2 answers

2
points
This was chosen as the best answer

Does this help? http://www.dreamincode.net/code/snippet980.htm

Answered about 6 years ago by John Catterfeld
  • Is using a regex faster? more complete? How is this better than `(field.value).replace(' ','');` Michael Martin-Smucker about 6 years ago
  • Hmm, so replace(' ','') doesn't work because it only replaces the first instance, but doesn't the expression in that link only trim white spaces at the beginning and end of the string? Michael Martin-Smucker about 6 years ago
0
points

To remove a space character, you'll want to replace it with an empty character: ''. JavaScript has a built-in replace() function that you can use to replace or remove a substring within a string.

Replacing a Space:

Let's say, for example, that you're saving the text from the text field into a variable named strInput. Running strInput.replace(' ', ''); will find the first space character and replace it with nothing (effectively removing it).

Replacing All Spaces:

You probably don't just want to remove one space character, though, you want to remove all of them. To do that, you'll need to use the replace function to replace all occurrences of the substring. To do this, you use the regular expression / /g instead of ' ', so your expression becomes strInput.replace(/ /g, '');. The "g" is the part that finds all occurrences.

Replacing All Whitespaces:

This would probably take care of what you want to do, but you might want to remove all white space characters, including new line characters. For this, you would use \s in your regular expression instead of a space. The final result is: strInput.replace(/\s/g, '');

Here's the jsFiddle version if you want to mess around with it: http://jsfiddle.net/qXyEw/

Answered about 6 years ago by Michael Martin-Smucker