d-_-b
d-_-b

Reputation: 23161

How to remove the extra spaces in a string?

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?

Upvotes: 83

Views: 116121

Answers (15)

Oleksandr Trach
Oleksandr Trach

Reputation: 1

const removeExtraSpaces = (str) => str.trim().split(' ').filter(x => x.length >= 1).join(' ')

Upvotes: -2

Talha
Talha

Reputation: 886

Here are functions that used to remove extra spaces.

removeExtraSpace used o remove all extra spaces from a paragraph.

removeExtraSpace used to remove all extra spaces from the right side of the paragraph.

leftExtraSpace used to remove all extra spaces from the left side of the paragraph.

let buggyString = "     The quick brown fox jumps      over the lazy dog    ";

const removeExtraSpace = (string) => string.trim().split(/ +/).join(' ');

function rightExtraSpace(string) {
  if (!string) {
    return string;
  }
  return string.replace(/\s+$/g, '');
}

function leftExtraSpace(string) {
  if (!string) {
    return string;
  }
  return string.replace(/^\s+/g, '');
}

console.log("removeExtraSpace => ", "'" + removeExtraSpace(buggyString) + "'");

console.log("rightExtraSpace => ", "'" + rightExtraSpace(buggyString) + "'");

console.log("leftExtraSpace => ", "'" + leftExtraSpace(buggyString)+ "'");

Upvotes: 0

Konstantin Vertinskiy
Konstantin Vertinskiy

Reputation: 93

Do not forget about new lines. Regular expression will replace them.

newString = string.split('\n').map((s) => s.replace(/\s+/g, ' ').trim()).join('\n');

Upvotes: 1

Alphonse Prakash
Alphonse Prakash

Reputation: 840

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"

Upvotes: -1

Ebner Silva
Ebner Silva

Reputation: 1


// 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;
}

Upvotes: -2

basit raza
basit raza

Reputation: 731

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

Upvotes: 20

Senthuran
Senthuran

Reputation: 1837

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

sentence.split(' ').filter(word => word).join(' ')

Upvotes: 4

Ido Bleicher
Ido Bleicher

Reputation: 857

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

Upvotes: 5

Chaitanya Munipalli
Chaitanya Munipalli

Reputation: 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);
        

Upvotes: -1

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

Upvotes: -1

Yhensel Benitez Tapia
Yhensel Benitez Tapia

Reputation: 61

I got the same problem and I fixed like this

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

Upvotes: 6

Alok Deshwal
Alok Deshwal

Reputation: 1126

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

Upvotes: 0

d-_-b
d-_-b

Reputation: 23161

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

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

Upvotes: 9

Hamish
Hamish

Reputation: 23316

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

Upvotes: 198

Ye Liu
Ye Liu

Reputation: 8976

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

Upvotes: 27

Related Questions