Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 594
Mangano Avatar asked Oct 08 '10 19:10

Mangano


3 Answers

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,"");
like image 103
Nick Craver Avatar answered Sep 30 '22 05:09

Nick Craver


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

var string= string.split(' ').join('');
like image 43
kennebec Avatar answered Sep 30 '22 04:09

kennebec


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.

like image 31
Jay Avatar answered Sep 30 '22 05:09

Jay