Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all white space from string JavaScript [duplicate]

How can I remove all the white space from a given string.

Say:

var str = "  abc de fog   ";
str.trim(); 

Gives abc de fog AND NOT abcdefog, which I want.

How can I get all the white space removed using JavaScript?

like image 510
user3566643 Avatar asked Jul 04 '14 21:07

user3566643


People also ask

How do you get rid of all whitespace in a string JavaScript?

Using Split() with Join() method To remove all whitespace characters from the string, use \s instead. That's all about removing all whitespace from a string in JavaScript.

How do you get rid of all whitespace in a string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.

How do I remove double spacing from a string?

Using regexes with "\s" and doing simple string. split()'s will also remove other whitespace - like newlines, carriage returns, tabs.

How do I replace multiple spaces in single space?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.


1 Answers

Use this:

str.replace(/\s+/g, '');

Instead of this:

str.trim()
like image 106
Cute_Ninja Avatar answered Oct 07 '22 11:10

Cute_Ninja