views:

65

answers:

3

How I could remove blank characters from a string in javascript?

A trim is very easy, but I don't know how extract a blank "inside" the string. For example

"222 334" -> "222334"

Thanks in advance

+7  A: 

You can use a regex, like this to replace all whitespace:

var oldString = "222 334";
var newString = oldString.replace(/\s+/g,"");

Or for literally just spaces:

var newString = oldString.replace(/ /g,"");
Nick Craver
A: 

Nick Craver has a good response, if you're OK with regex, go for it.

I just want to add that you can do this without Regex as well. You can just use a normal JavaScript replace(), using the parameters (" ", "") to replace all whitespace with empty strings.

Update: Whoops, this won't work with multiple whitespaces.

JavaScript replace method on w3schools.

Cyrena
This won't get tabs.
Stefan Kendall
This will also only replace the *first* occurrence of a space, not all of them.
Nick Craver
Stefan: If tabs need to be pulled as well, then of course, Nick Craver's regex is best.
Cyrena
A: 

You can also do this without a regular expression or a replace-

var str=str.split(' ').join('');

kennebec