43

Possible Duplicate:
Replace multiple whitespaces with single whitespace in JavaScript string

I have used trim function to remove the white spaces at the beginning and end of the sentences. If there is to much white spaces in between words in a sentence, is there any method to trim?

for example

"abc                  def. fds                            sdff."
Slbox
  • 10,957
  • 15
  • 54
  • 106
Lakshmitha
  • 675
  • 3
  • 11
  • 17

6 Answers6

79

try

"abc                  def. fds                            sdff."
 .replace(/\s+/g,' ')

or

"abc                  def. fds                            sdff."
     .split(/\s+/)
     .join(' ');

or use this allTrim String extension

String.prototype.allTrim = String.prototype.allTrim ||
     function(){
        return this.replace(/\s+/g,' ')
                   .replace(/^\s+|\s+$/,'');
     };
//usage:
alert(' too much whitespace     here   right?  '.allTrim());
   //=> "too much whitespace here right?"
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 1
    Got something to convert tabs and line breaks, too? I was looking for something that could compress code to ignore layout for functional comparison, basically to compare everything in two pieces of code except for the style they're written in. – Kelvin Shadewing Feb 21 '16 at 23:42
  • `\s+` is for all whitespace, including tabs and line breaks. – KooiInc Feb 22 '16 at 07:13
  • 1
    Why the "g" in those regular expressions? – Daniel Möller Dec 23 '16 at 01:18
  • 1
    Hi @Daniel, see https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags – KooiInc Dec 23 '16 at 10:31
  • This doesn't deal properly with line breaks, as it replaces all multiples with a space. – Chris Peacock Jan 30 '23 at 18:34
  • @ChrisPeacock Sure. Use `.replace(/ +/g,' ').replace(/^\n +|^ +| +$|\n +$/gm,'')` if you need to keep the line breaks – KooiInc Jan 30 '23 at 22:21
  • Thanks @KooiInc. I tried that, there were still some problems, I ended up using this: `.replace(/^[ \t]+/gm, '') .replace(/[ \t]+/g, ' ') .replace(/\n{2,}/g, '\n') .trim()` – Chris Peacock Jan 31 '23 at 18:17
37
var str = 'asdads   adasd    adsd';
str = str.replace(/\s+/g, ' ');
Shef
  • 44,808
  • 15
  • 79
  • 90
10

You can trim multiple consecutive spaces down to only one space with this Javascript:

var str = "abc def.  fds    sdff.";
str = str.replace(/\s+/g, " ");

If you meant something other than multiple consecutive spaces, then please clarify in your question what you meant.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
4

I think what you're looking for is JavaScript's string.replace() method.

If you want all whitespace removed, use this:

"abc def. fds sdff.".replace(/\s/g, '');
Returns: "abcdef.fdssdff."

If you want only double-spaces removed, use:

"abc   def.  fds      sdff.".replace(/\s\s/g, ' ');
Returns: "abc def. fds sdff."

If you want the space left after a period, use:

"abc def. fds   sdff.".replace(/[^.]\s/g, '')
Returns: "abcdef. fdssdff."
Ehryk
  • 1,930
  • 2
  • 27
  • 47
1

Refer to the following code part which used rejex in javascript to remove duplicate white spaces.

function trim(value) {
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   var obj = / +/g;
   temp = temp.replace(obj, " ");
   if (temp == " ") { temp = ""; }
   return temp;
}
1
value.replace("  ", " ");

This should do the trick, it just replaces 2 white spaces to one, until you get only 1 white space.

samn
  • 2,699
  • 4
  • 20
  • 24
  • 6
    That will only replace the first occurrence of two consecutive spaces. In JavaScript, `replace` behaves a bit "strange". If you want to replace all occurrences of a substring, you have to use a regular expression with the `g`lobal modifier. But in any case, replacing is not "recursive". The substitute is not checked again whether it can be replaced. Meaning, if your string contains three spaces, you will end up with two, not one. – Felix Kling Oct 14 '11 at 07:31
  • Oh okay, thanks for the explanation. It seemed logical in my head :) – samn Oct 14 '11 at 07:39
  • What about `replaceAll`? – parsecer May 25 '23 at 19:28