215

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?

2

12 Answers 12

400

Something like this:

const str = "  a  b     c  "
const result = str.replace(/\s+/g, ' ').trim()

console.log('result', result)
console.log('result.length', result.length)

Sign up to request clarification or add additional context in comments.

10 Comments

@Me Please read the question carefully: "each time there's more than only one whitespace I'd like it be only one".
Isn't it obvious? it replaces more than 1 whitespace char with 1 whitespace char. (the desired result)
@CiaranG It's a regular expresion
@Wardy, close :-). It replaces one OR more with one space (but indeed, the desired result).
What 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
|
58

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();

1 Comment

Augmenting prototype of the standard object is a really controversial pattern. I wouldn't recommend it for such a basic question.
19

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.

1 Comment

This combines even the built in trim() for strings, which is awesome.
16

using a regular expression with the replace function does the trick:

string.replace(/\s/g, "")

2 Comments

This solution is wrong per the question. And I really wonder why you posted it two days after a better solution has been posted ...
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.
12

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.

1 Comment

I 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 ' '.
8

jQuery.trim() works well.

http://api.jquery.com/jQuery.trim/

1 Comment

Just remember that this doesn't remove all whitespace. Quoting the docs: "Remove the whitespace from the beginning and end of a string."
8

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.

2 Comments

+1 for the "ready for use" example .. I was going to post it my self
EXACTLY what I was looking for, awesome!
4

var x = " Test Test Test ".split(" ").join(""); alert(x);

1 Comment

It 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 !
2

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, ' ').

Comments

1

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

2 Comments

Tabs are already covered by \s. Unnecessarily complex regex, might as well just write /\s+/g.
Interestingly, 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.
0

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.

Comments

0

Use this function:

function removeDupliSpaces(string) {
    return string.replace(/\s+/g, ' ').trim();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.