Skip to content
Related Articles

Related Articles

How to remove white spaces from a string using jQuery ?

Improve Article
Save Article
  • Last Updated : 22 Mar, 2021
Improve Article
Save Article

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.


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.



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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!