How to remove extra white space from string using JavaScript?

   JavaScript

Sometimes the extra space starts appearing in any sentence, like ” I love JavaScript “ which becomes hardly readable, specially in case of multi lines or paragraphs. Below solution explains how you can remove extra white space from a String using JavaScript.

Solution

var str = "     I      love   JavaScript        ";
var newStr = str.replace(/\s+/g, ' '); // Use regex for correct result
console.log(newStr);

//Output
"I love JavaScript"
Tags: JavaScriptRemove Extra White SpaceReplaceTrim

Leave a Comment