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:

  • str: This parameter is the string to be trimmed.

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.



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:




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.