JavaScript

How to replace multiple spaces with single space in JavaScript

You can use the replace() method in JavaScript to replace multiple spaces in a string with a single space, like the following example:
 

How to replace multiple spaces with single space in JavaScript
var str = 'Welcom          to      StackHowTo.com!';

var str = str.replace(/  +/g, ' ');

alert(str);

Output:

Welcom to StackHowTo.com!

However, the difference is not noticeable if you display this string of characters on a web page, because browsers treat multiple spaces as one space, unless you keep spaces.
 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *