How to remove duplicate spaces in a string?

Possible duplicate:
Removing space from a string in JavaScript

I used the trim function to remove spaces at the beginning and end of sentences. If there are many spaces between words in a sentence between words, is there a way to crop?

eg

"abc def. fds sdff." 
+8
javascript regex
source share
6 answers

to try

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

or

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

or use this extension allTrim String

 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?" 
+20
source share
 var str = 'asdads adasd adsd'; str = str.replace(/\s+/g, ' '); 
+20
source share

I think you are looking for the JavaScript method string.replace ().

If you want to remove all spaces, use this:

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

If you want to remove only two spaces, use:

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

If you want to leave a space after a period, use:

 "abc def. fds sdff.".replace(/[^.]\s/g, '') Returns: "abcdef. fdssdff." 
+3
source share

You can trim multiple consecutive spaces to one space using this Javascript:

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

If you meant something other than a few consecutive spaces, please specify in your question what you had in mind.

+2
source share

Refer to the next piece of code that used rejex in javascript to remove duplicate 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
source share
 value.replace(" ", " "); 

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

+1
source share

All Articles