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

The JavaScript trim() method is used when we need to remove all whitespace from the 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 the 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 whitespace (if available) from both sides of the string.

JavaScript trim() example

Let me create an example that uses the length property to get the length of the 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 »


Liked this post? Share it!