I have strings with extra whitespace characters. Each time there's more than one whitespace, I'd like it be only one. How can I do this using JavaScript?
-
2remove duplicate whitespace from the end/beginning, or anywhere in the text? – ninjagecko May 28 '11 at 17:24
-
1Possible duplicate of [Regex to replace multiple spaces with a single space](https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space) – Muhammad Omar ElShourbagy Aug 08 '17 at 15:33
11 Answers
Something like this:
var s = " a b c ";
console.log(
s.replace(/\s+/g, ' ')
)
-
31@Me Please read the question carefully: "each time there's more than only one whitespace I'd like it be only one". – bjornd Dec 29 '12 at 09:45
-
5Isn't it obvious? it replaces more than 1 whitespace char with 1 whitespace char. (the desired result) – War Mar 22 '13 at 16:05
-
4
-
1@Wardy, close :-). It replaces one OR more with one space (but indeed, the desired result). – greenoldman Jan 11 '15 at 13:00
-
meh ... semantics ... i was explaining the visible change ... I thought the replace function by default only replaced the first instance, would this still work with a longer string that had more than 1 instance of the regex match? (by replacing all) – War Jan 12 '15 at 11:09
-
-
1What if one wants to replace 1+ whitespaces with the same kind of whitespace? (e.g. 2+ spaces with a space and 3 newlines with a newline, etc.) if there are both newlines and spaces it would have to be replaced by a newline whereas if there are both spaces and tabs it would have to be replaced by a space – Tom Jun 28 '15 at 15:40
-
-
@user21 the `/g` means to match every instance instead of just the first instance, see [MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags). – doubleDown Feb 09 '16 at 07:53
You can augment String to implement these behaviors as methods, as in:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
This now enables you to use the following elegant forms to produce the strings you want:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();

- 672
- 4
- 2
-
17Augmenting prototype of the standard object is a really controversial pattern. I wouldn't recommend it for such a basic question. – bjornd Nov 02 '12 at 09:06
Here's a non-regex solution (just for fun):
var s = ' a b word word. word, wordword word ';
// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"
// or ES2015:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
Can even substitute filter(n => n)
with .filter(String)
It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.

- 118,978
- 58
- 307
- 400
-
This combines even the built in trim() for strings, which is awesome. – Zahari Kitanov Jan 11 '21 at 12:17
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")

- 523
- 4
- 12
-
2This solution is wrong per the question. And I really wonder why you posted it two days after a better solution has been posted ... – Sebastian Mach Sep 04 '15 at 16:48
-
I think at the time, only this code worked for me. I can't go back on that to confirm. I obviously would have tried the best solution first. Also, upon checking it in chrome console, both solutions seemed to work. Interestingly however, when I copied the result to this comment box, it showed that my solution didn't work for multiple whitespaces. Maybe you can help me to understand why. I guess it's a chrome error? Try running my code in chrome console and let me know. – Roger Gajraj Sep 13 '15 at 05:05
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?
If that's the case, you'll need a regex like this:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
mystring = mystring.replace(/\s+$/g,' ');
Hope that helps.

- 166,037
- 39
- 233
- 307
-
5I like the simplicity of your regex, @Spudley, but won't your code replace runs of whitespace at the beginning and end with a single space character? I thought the goal was to remove the whitespace from the ends entirely, in which case the replacement string should be `''` instead of `' '`. – Randall Cook Oct 16 '12 at 18:44
jQuery.trim() works well.

- 5,106
- 2
- 25
- 30
-
14Just remember that this doesn't remove all whitespace. Quoting the docs: "Remove the whitespace *from the beginning and end of a string*." – Jonik Aug 22 '12 at 10:52
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
- I want to replace multiple occurences of whitespace inside the string with a single space
- ...and... I do not want whitespaces in the beginnin or end of the string (trim)
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.

- 126
- 1
- 3
var x = " Test Test Test ".split(" ").join(""); alert(x);

- 87
- 1
- 2
-
5It works but it is not smart coding. This code is slower than a RegEx. I wonder if Split() does not use RegEx to split a string ! – Farandole Oct 31 '12 at 19:40
Try this.
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
the result will be
string 1
What happened here is that it will trim the outside spaces first using trim()
then trim the inside spaces using .replace(/\s+/g, ' ')
.

- 1,037
- 10
- 20
How about this one?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs "my test string with crazy stuff is cool "
This one gets rid of any tabs as well

- 11,147
- 6
- 55
- 64
-
Tabs are already covered by `\s`. Unnecessarily complex regex, might as well just write `/\s+/g`. – Anders Rabo Thorbeck Jan 29 '20 at 15:09
-
1Interestingly, this is the only answer that uses `{2,}`. The `9999` is unnecessary and even potentially wrong. I'm not sure if only matching and replacing 2 or more spaces is beneficial or detrimental to the performance. – wensveen Nov 29 '21 at 11:42
If you want to restrict user to give blank space in the name just create a if statement and give the condition. like I did:
$j('#fragment_key').bind({
keypress: function(e){
var key = e.keyCode;
var character = String.fromCharCode(key);
if(character.match( /[' ']/)) {
alert("Blank space is not allowed in the Name");
return false;
}
}
});
- create a JQuery function .
- this is key press event.
- Initialize a variable.
- Give condition to match the character
- show a alert message for your matched condition.

- 5,007
- 6
- 42
- 54

- 9
- 1