-3

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
dazzafact
  • 2,570
  • 3
  • 30
  • 49

2 Answers2

2

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>
blex
  • 24,941
  • 5
  • 39
  • 72
1
$new = $new.split(/ +/).join(' ');
Alvin Thompson
  • 5,388
  • 3
  • 26
  • 39