Trim string in Jquery

In web development, displaying content to webpage can dynamically generated. Thus, there can be human error like extra space or tab or new line is added by mistake. But display same data as inputted can be bad for user experience. For situation like this, we have to remove white space from content or before showing or before adding into database.

With jQuery, we can easily remove white space from any string values. White space can be spaces, new lines or tabs from the beginning or ending of string.

The $.trim() or jQuery.trim() function are used to remove white space from string variables in jQuery. This function takes one parameter as string type and returns clean string. However, it will only remove white space from beginning or ending. White space in middle will be unchanged.

Let's take an example where user enter some text input in text-area which can contains white space and user can remove white space by clicking button using jQuery.

<!DOCTYPE html>
<html lang="en">
        <meta charset="utf-8">
        <title>Remove White Space from Strings Using jQuery trim() function</title>
        <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=""></script>
            function cleanTextarea(){
                var userInput = $("#user-input").text();
                var trimmedInput = $.trim(userInput);

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


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

Share your thoughts

Ask anything about this examples