Remove all whitespace from the string in JavaScript

In this tutorial, we will see a javascript program to remove all the whitespace from the string.

A string can have a leading or trailing whitespace that is at the beginning or at the end of the screen for whatever reasons.

We can remove these spaces using a simple regex.

let text = "   Learnersbucket    ";
text = text.replace(/^\s+|\s+$/g, "");

console.log(text);
// "Learnersbucket"

This also removes the whitespace formed using the \n.

let text = "\n\n Learnersbucket  \n \n";
text = text.replace(/^\s+|\s+$/g, "");

console.log(text);
// "Learnersbucket"