Remove whitespace from string in jQuery

Remove Whitespace from string in jQuery is important when displaying dynamic content on a webpage. Sometimes, users or processes accidentally add extra spaces, tabs, or new lines, and these mistakes reduce the quality of the user experience. To keep content clean and consistent, developers should remove unnecessary white space before displaying it or saving it to a database.

With jQuery, you can remove white space from any string value, including spaces, tabs, or new lines at the beginning or end of a string.

The $.trim() or jQuery.trim() function is used to remove white space from string variables in jQuery. This function takes one parameter as string type and returns a clean string. However, it will only remove white space from the beginning or end. It will not make any changes on the white space in the middle.

Let’s take an example where the user enters some text input in the text area which can contain white space and the user can remove white space by clicking a button using jQuery.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Remove White Space from Strings Using jQuery trim() function</title>
    </head>
    <body>
        <h3>Enter string into below textarea</h3>
        <textarea id="user-input" rows="10" col="10"> user can add white space at beginning or ending like     this. White space in middle will be ignored.        </textarea>
        <button type="button" onclick="cleanTextarea()">Clean Textarea</button>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script>
            function cleanTextarea(){
                var userInput = $("#user-input").text();
                var trimmedInput = $.trim(userInput);
                $("#user-input").html(trimmedInput);
            }
        </script>
    </body>
</html>

In the above example, we have created a text area and given some default values with white space in it. We have also created a button with an onclick attribute. So whenever the user clicks on that button then our function will get the value of that text area and trim it. It will also set trimmed value as text-area input programmatically.

Conclusion

In this article, we have taken a practical example of a trim() function in jQuery. Here, we just have demonstrated a simple use case for white space removal using jQuery. You can implement it into any other functionality as per your requirements.

You can quickly verify array values using How to Check Value Exists in Array or Not using jQuery, which shows simple ways to detect if a value is present.