Skip to content
Related Articles

Related Articles

Improve Article
How to remove white spaces from a string using jQuery ?
  • Last Updated : 22 Mar, 2021

In this article, we will see how to remove the white spaces from string using jQuery. To remove the white spaces, we will use trim() method. The trim() method is used to remove the white spaces from the beginning and end of a string.

Syntax:

jQuery.trim( str )

Parameters: This method accepts a single parameter string that is to be trimmed.

In this case, we write string containing white spaces in <pre> tag and then apply trim() method to remove all white spaces from starting and ending position. After removing the white spaces we use html() method to display the trimmed string.

Example:

HTML




<!DOCTYpe html>
<html>
  
<head>
    <title>
        How to remove white space from
        a string using jQuery?
    </title>
  
    <script src=
    </script>
  
    <script>
        $(document).ready(function () {
            $("h1").css("color", "green");
            $("button").click(function () {
                $(".str").html("String without whitespaces");
                var str = $(".string").text();
                var trimStr = $.trim(str);
                $(".res-string").html(trimStr);
            })
        });
    </script>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
  
    <h3>
        How to remove white space from
        a string using jQuery?
    </h3>
  
    <h4>String containing white spaces</h4>
    <pre class="string">    GeeksforGeeks       </pre>
  
    <button>Trim String</button>
  
    <h4 class="str"></h4>
    <pre class="res-string"></pre>
</body>
  
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :