18

How would I remove blank characters from a string in JavaScript?

A trim is very easy, but I don't know how to remove them from inside the string. For example:

222 334 -> 222334

4 Answers 4

52

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,"");
Sign up to request clarification or add additional context in comments.

1 Comment

This will work for most use cases, however not for unicode space characters.
14

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

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

Comments

8

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.

3 Comments

This will also only replace the first occurrence of a space, not all of them.
Stefan: If tabs need to be pulled as well, then of course, Nick Craver's regex is best.
Thanks Cyrena, I have to add also that you are very beautiful
0

You can simply use trim().

See docs here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.