How to replace multiple spaces with single space in JavaScript

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the JavaScript replace() Method

You can use the JavaScript replace() to replace the multiple spaces inside a string, like this:

  • <script type="text/javascript">
  •     var myStr = 'The     quick   brown  fox';
  •     alert(myStr);  // Output 'The     quick   brown  fox'
  •     
  •     var newStr = myStr.replace(/  +/g, ' ');
  •     alert(newStr);  // Output 'The quick brown fox'
  • </script>

However, the difference is not visible if you print those strings on a web page, because browsers treat multiple spaces as single space unless you preserve white space.

  • <script type="text/javascript">
  •     var myStr = 'The  quick brown fox';
  •     document.write('<p>' + myStr + '</p>'); // Browser doesn't display multiple spaces
  •     var newStr = myStr.split(' ').join('-');
  •     document.write('<p>' + newStr + '</p>'); // Print 'The--quick-brown-fox'
  •     
  •     var myStr = myStr.replace(/  +/g, ' ');
  •     document.write('<p>' + myStr + '</p>');
  •     var newStr = myStr.split(' ').join('-');
  •     document.write('<p>' + newStr + '</p>');  // Print 'The-quick-brown-fox'
  • </script>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.