Open In App

How to remove white spaces from a string using jQuery ?

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 )

Parameter: 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: This example illustrates the removal of the white spaces from a string using jQuery.

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:

gfg_img



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads