Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all multiple spaces in Javascript and replace with single space [duplicate]

How can I automatically replace all instances of multiple spaces, with a single space, in Javascript?

I've tried chaining some s.replace but this doesn't seem optimal.

I'm using jQuery as well, in case it's a builtin functionality.

like image 907
Alex Avatar asked Jul 20 '10 03:07

Alex


People also ask

How do I replace multiple spaces with one 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.

How do you remove double spacing in JavaScript?

Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s . Expand the whitespace selection from a single space to multiple using the \s+ RegEx.

How do I replace multiple spaces with single space in bash?

Continuing with that same thought, if your string with spaces is already stored in a variable, you can simply use echo unquoted within command substitution to have bash remove the additional whitespace for your, e.g. $ foo="too many spaces."; bar=$(echo $foo); echo "$bar" too many spaces.


2 Answers

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,''); 

Credit: The above regex was taken from Regex to replace multiple spaces with a single space

like image 94
Josiah Avatar answered Oct 15 '22 01:10

Josiah


There are a lot of options for regular expressions you could use to accomplish this. One example that will perform well is:

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

See this question for a full discussion on this exact problem: Regex to replace multiple spaces with a single space

like image 29
Greg Shackles Avatar answered Oct 15 '22 00:10

Greg Shackles