Q:

How to replace multiple spaces with single space in JavaScript

0

How to replace multiple spaces with single space in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the JavaScript replace() method

You can simply use the JavaScript replace() to replace the multiple spaces inside a string.

Let's take a look at the following example to understand how it basically works:

<script>
    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>
    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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to detect click inside iframe using JavaScript... >>
<< How to check whether a value is numeric or not in ...