Open In App

JQuery | trim() Method

This trim() Method in jQuery is used to remove the whitespace from the beginning and end of a string

Syntax:



jQuery.trim( str )

Parameters: This method accept a single parameter which is mentioned above and described below:

Return Value: It returns the string after removing the whitespaces.



Below example illustrate the use of trim() method in jQuery:
Example 1: In this example, the trim() method removes the tab and spaces at the start and at the end of the string.




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8">
    <title>JQuery | trim() method</title>
    <script src=
    </script>
    <style>
        div {
            color: blue;
        }
    </style>
</head>
  
<body style="text-align:center;">
  
    <h1 style="color: green"
        GeeksforGeeks 
    </h1>
  
    <h3>JQuery | trim() method</h3>
    <pre id="bb"></pre>
  
    <script>
        $("#bb").html(
            $.trim("     A computer science portal for geeks     "));
    </script>
  
</body>
  
</html>                                            


Output:

Example 2: In this example, the trim() method removes the white spaces from multiple line.




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8">
    <title>JQuery | trim() method</title>
    <script src=
    </script>
    <style>
        pre {
            color: green;
        }
    </style>
</head>
  
<body style="text-align:center;">
  
    <h1 style="color: green"
        GeeksforGeeks 
    </h1>
  
    <h3>JQuery | trim() method</h3>
    <pre id="geeks"></pre>
    <pre id="geeks1"></pre>
    <script>
        var varr = "\nIt removes all newlines, \n spaces"+
            " and \n tabs from the beginning and end of string.\n"
        var varr1 = " \n Whitespace in the middle"+
            " of string are preserved\n"
        $("#geeks").html("<b>Original : <br></b>" 
                         + varr + varr1);
        $("#geeks1").html("<b>Trimmed : <br></b>"
                          + $.trim(varr) + $.trim(varr1));
    </script>
  
</body>
  
</html>       


Output:

Article Tags :