Javascript - Remove space- not breaks

74 views Asked by At

How can i remove space in a string, without removing the breaks inside?

$new=$new.replace(/\s+/g,' '); //not working correct


this       is a test.
please    remove only   the
Space not
the       breaks inside


this is a test.
please remove only the
Space not
the breaks
2

There are 2 answers

3
blex On BEST ANSWER

Just use / +/g:

$new = document.getElementById('content').innerHTML;

$new = $new.replace(/ +/g,' ');
// or $new = $new.replace(/(\s(?=\s))+/g,'');
 
document.getElementById('result').innerHTML = $new;
<pre id="content">
this       is a test.
please    remove only   the
Space not
the       breaks inside
</pre>

<pre id="result">
</pre>

9
Alvin Thompson On
$new = $new.split(/ +/).join(' ');