JavaScript trim() | Remove whitespace from beginning and end of string

The JavaScript trim() method is used when we need to remove all whitespaces from beginning and end of the string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "   JavaScript is Fun.    ";
      let res = myString.trim();
      document.getElementById("xyz").innerHTML = res;
   </script>
   
</body>
</html>
Output

JavaScript trim() Syntax

The syntax of trim() method in JavaScript is:

string.trim()

The trim() method does not change the original string. Rather it returns the same string after removing all whitespaces (if available) from both side of the string.

JavaScript trim() Example

Let me create an example that uses the length property to get the length of same string before and after using the trim() method:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Length (before trim()) = <b><span id="a"></span></b></p>
   <p>Length (after trim()) = <b><span id="b"></span></b></p>

   <script>
      let myString = "   JavaScript is Fun.    ";

      document.getElementById("a").innerHTML = myString.length;
      let res  = myString.trim();
      document.getElementById("b").innerHTML = res.length;
   </script>
   
</body>
</html>
Output

Length (before trim()) =

Length (after trim()) =

JavaScript Online Test


« Previous Tutorial Next Tutorial »