How to remove the extra spaces in a string?
Asked Answered
P

15

81

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?

Proportionate answered 7/6, 2013 at 1:1 Comment(1)
Look at using underscore.string, there are many clean methods like this that will help you out, does not require underscore.Cordula
N
194

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();
Neolamarckism answered 7/6, 2013 at 1:4 Comment(2)
thanks! that makes sense... btw this is missing a function to trim (first and last single spaces) :)Proportionate
works perfectly even after 8 years LOL ;3Bellew
A
26
string.replace(/\s+/g, ' ').trim()
Apsis answered 7/6, 2013 at 1:4 Comment(0)
C
18

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
Chrysolite answered 18/9, 2019 at 17:14 Comment(1)
This will turn 2+ spaces into 0 space. You might want to change it to a single space (' ') instead of ('')Wedurn
P
9

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

string.replace(/\s+/g,' ').trim()
Proportionate answered 7/6, 2013 at 1:4 Comment(2)
convert to a byte array, manually iterate through it and output to a new byte array. Convert the new array to a string.... better?Ullyot
This is pure JS, not jQuery.Karleen
B
6

I got the same problem and I fixed like this

Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
Birdbath answered 29/1, 2020 at 18:21 Comment(0)
Q
5

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

Quintillion answered 27/8, 2021 at 10:42 Comment(0)
H
4

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

sentence.split(' ').filter(word => word).join(' ')
Hurter answered 19/9, 2021 at 8:23 Comment(1)
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).Unnamed
R
1

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

newString = string.split('\n').map((s) => s.replace(/\s+/g, ' ').trim()).join('\n');
Rafi answered 19/12, 2023 at 13:38 Comment(0)
C
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));
Cattegat answered 28/12, 2019 at 5:24 Comment(1)
Involves extending native objects, which is considered an anti-pattern.Keystone
B
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);
Badtempered answered 20/10, 2020 at 6:3 Comment(1)
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.Andryc
H
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;
}

Hezekiah answered 18/2, 2022 at 19:37 Comment(0)
G
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"

Goodale answered 12/3, 2022 at 18:37 Comment(0)
D
0

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

Durware answered 13/1, 2024 at 23:49 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Quisling
C
0

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)+ "'");
Circumambulate answered 29/3, 2024 at 20:1 Comment(0)
A
-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);
        
Adenoma answered 21/10, 2020 at 5:10 Comment(1)
it may work but there is much simpler solution.Gravamen

© 2022 - 2025 — McMap. All rights reserved.