I have some text which looks like this -
\" tushar is a good boy \"
Using javascript I want to remove all the extra white spac
Try this:
str.replace(/\s+/g, ' ').trim()
If you don't have trim
add this.
Trim string in JavaScript?
Since everyone is complaining about .trim()
, you can use the following:
str.replace(/\s+/g,' ' ).replace(/^\s/,'').replace(/\s$/,'');
JSFiddle
Try:
str.replace(/^\s+|\s+$/, '')
.replace(/\s+/, ' ');
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"
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.
This works nicely:
function normalizeWS(s) {
s = s.match(/\S+/g);
return s ? s.join(' ') : '';
}