Reputation: 10992
I have some text which looks like this -
" tushar is a good boy "
Using javascript I want to remove all the extra white spaces in a string.
The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this -
"tushar is a good boy"
I am using the following code at the moment-
str.replace(/(\s\s\s*)/g, ' ')
This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.
Upvotes: 24
Views: 113774
Reputation: 6552
This works nicely:
function normalizeWS(s) {
s = s.match(/\S+/g);
return s ? s.join(' ') : '';
}
Upvotes: 8
Reputation: 385
Since everyone is complaining about .trim()
, you can use the following:
str.replace(/\s+/g,' ' ).replace(/^\s/,'').replace(/\s$/,'');
Upvotes: 5
Reputation: 234
try
var str = " tushar is a good boy ";
str = str.replace(/^\s+|\s+$/g,'').replace(/(\s\s\s*)/g, ' ');
first replace is delete leading and trailing spaces of a string.
Upvotes: -1
Reputation: 785146
This can be done in a single String#replace
call:
var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// gives: "tushar is a good boy"
Upvotes: 37
Reputation: 190945
Try this:
str.replace(/\s+/g, ' ').trim()
If you don't have trim
add this.
Upvotes: 4