String strip() in JavaScript

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right



Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.