79

What function will turn this contains spaces into this contains spaces using javascript?

I've tried the following, using similar SO questions, but could not get this to work.

var string = " this contains   spaces ";

newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,'');  //"thiscontainsspaces"

Is there a simple pure javascript way to accomplish this?

Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35
d-_-b
  • 21,536
  • 40
  • 150
  • 256
  • 1
    Look at using underscore.string, there are many clean methods like this that will help you out, does not require underscore. – adrian Jun 07 '13 at 01:10

12 Answers12

185

You're close.

Remember that replace replaces the found text with the second argument. So:

newString = string.replace(/\s+/g,''); // "thiscontainsspaces"

Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!

newString = string.replace(/\s+/g,' ').trim();
d-_-b
  • 21,536
  • 40
  • 150
  • 256
Hamish
  • 22,860
  • 8
  • 53
  • 67
25
string.replace(/\s+/g, ' ').trim()
Ye Liu
  • 8,946
  • 1
  • 38
  • 34
17

Try this one, this will replace 2 or 2+ white spaces from string.

const string = " this contains   spaces ";    
string.replace(/\s{2,}/g, ' ').trim() 
Output
this contains spaces
basit raza
  • 661
  • 2
  • 6
  • 18
  • 2
    This will turn 2+ spaces into 0 space. You might want to change it to a single space (' ') instead of ('') – Dror Bar Aug 02 '21 at 14:14
9

I figured out one way, but am curious if there is a better way...

string.replace(/\s+/g,' ').trim()
d-_-b
  • 21,536
  • 40
  • 150
  • 256
6

I got the same problem and I fixed like this

Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
4

I think images always explain it's good, basically what you see that the regex \s meaning in regex is whitespace. the + says it's can be multiply times. /g symbol that it's looks globally (replace by default looks for the first occur without the /g added). and the trim will remove the last and first whitespaces if exists.

Finally, To remove extra whitespaces you will need this code:

newString = string.replace(/\s+/g,' ').trim();

enter image description here

Ido Bleicher
  • 709
  • 1
  • 9
  • 19
3

We can use the below approach to remove extra space in a sentence/word.

sentence.split(' ').filter(word => word).join(' ')
Senthuran
  • 1,583
  • 2
  • 15
  • 19
  • This one is pretty interesting too. I found relevant to note that this solution doesn't remove tabs or line breaks, unlike the `/\s+/g` regex. Also the filter could be `.filter(Boolean)`. – Daniel Mitre Sep 23 '21 at 17:23
0

Raw Javascript Solution:

var str = '  k                                     g  alok   deshwal';
function removeMoreThanOneSpace() {
    String.prototype.removeSpaceByLength=function(index, length) {
        console.log("in remove", this.substr(0, index));
        return this.substr(0, index) + this.substr(length);
    }
    for(let i  = 0; i < str.length-1; i++) {
        if(str[i] === " " && str[i+1] === " ") {
            str = str.removeSpaceByLength(i, i+1);
            i = i-1;
        }
    }
    return str;
}
console.log(removeMoreThanOneSpace(str));
Alok Deshwal
  • 1,128
  • 9
  • 20
0
var s=" i am a student "
var r='';
console.log(s);
var i,j;
j=0;
for(k=0; s[k]!=undefined; k++);// to calculate the length of a string

for(i=0;i<k;i++){
if(s[i]!==' '){
for(;s[i]!==' ';i++){
r+=s[i];
}
r+=' ';
}
}
console.log(r);
  • 4
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – 54ka Oct 20 '20 at 06:08
0

// Here my solution

const trimString = value => {

  const allStringElementsToArray = value.split(''); 
  // transform "abcd efgh" to ['a', 'b', 'c', 'd',' ','e', 'f','g','h']

  const allElementsSanitized = allStringElementsToArray.map(e => e.trim());
  // Remove all blank spaces from array

  const finalValue = allElementsSanitized.join('');
  // Transform the sanitized array ['a','b','c','d','e','f','g','h'] to 'abcdefgh'

  return finalValue;
}

0

I have tried regex to solve this problem :

let temp=text.replace(/\s{2,}/g, ' ').trim() 
console.log(temp);

input="Plese complete your work on Time"

output="Please complete your work on Time"

Alphonse Prakash
  • 804
  • 7
  • 17
-1
//This code remove extra spaces with out using "string objectives" 
      s="                 This Is   Working On      Functions  "
            console.log(s)
            final=""; 
            res='';
        function result(s) {
         for(var i=0;i<s.length;i++)
            {    
                if(!(final==""&&s[i]==" ")&&!(s[i]===" "&& s[i+1] ===" ")){ 
              final+=s[i]; 
               }
            }
           
            console.log(final);
        }
        result(s);