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?

88320 次浏览
string.replace(/\s+/g, ' ').trim()

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

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

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

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

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

I got the same problem and I fixed like this

Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
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);
//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);
        

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

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

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

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


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"