开发者

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

开发者 https://www.devze.com 2023-01-19 02:30 出处:网络
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:

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


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,"");


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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消