Replace multiple whitespaces with single whitespace in JavaScript string

JavascriptStringTrim

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Something like this:

var s = "  a  b     c  ";

console.log(
  s.replace(/\s+/g, ' ')
)

Solution 2 - Javascript

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

Solution 3 - Javascript

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

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

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.

Solution 6 - Javascript

jQuery.trim() works well.

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioneve View Question on Stackoverflow
Solution 1 - JavascriptbjorndView Answer on Stackoverflow
Solution 2 - Javascriptgui pnView Answer on Stackoverflow
Solution 3 - JavascriptRoger GajrajView Answer on Stackoverflow
Solution 4 - JavascriptvsyncView Answer on Stackoverflow
Solution 5 - JavascriptSpudleyView Answer on Stackoverflow
Solution 6 - Javascriptchug2kView Answer on Stackoverflow
Solution 7 - JavascriptMarkku UttulaView Answer on Stackoverflow
Solution 8 - JavascriptPraveen Kumar ThalluriView Answer on Stackoverflow
Solution 9 - JavascriptRichard VergisView Answer on Stackoverflow
Solution 10 - Javascriptuser3413723View Answer on Stackoverflow
Solution 11 - JavascriptAbhijit BIswasView Answer on Stackoverflow