Skip to content
Related Articles

Related Articles

String strip() in JavaScript

Improve Article
Save Article
Like Article
  • Last Updated : 08 Jun, 2020

The task here is to remove all leading and trailing spaces and tabs from the string. We will use some methods to reach the goal.

Method 1: Here, we will be using trim() method. We can strip a string using trim() method and can remove unnecessary trailing and leading spaces and tabs from the string.

Example:

HTML




<!DOCTYPE html>
<html>
<head>
    <title>String strip() for JavaScript</title>
</head>
<body>
    <script>
        var string="    GeeksforGeeks     ";
        console.log("Before string:'"+string+"'");
          
        console.log("After string :'"+string.trim()+"'");
    </script>
</body>
</html>

Output:

Method 2: Here we will be making a user-defined function. We will be writing a JavaScript to strip the string and to remove unnecessary spaces.

Example:

HTML




<!DOCTYPE html>
<html>
   <head>
      <title>String strip() for JavaScript</title>
   </head>
   <body>
       <script>
          function strip(string) {
              return string.replace(/^\s+|\s+$/g, '');
        }
          
        var string="    GeeksforGeeks     ";
        console.log("Before string:'"+string+"'");
           
        console.log("After string :'"+strip(string)+"'");
      </script>
  </body>
</html>


Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!