In web development, displaying content to a webpage can be dynamically generated. Thus, there can be a human error like extra space or tab or new line is added by mistake. But displaying same data as input can be bad for user experience. For situations like this, we have to remove white space from the content before showing or before adding into a 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 end of 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 clean string. However, it will only remove white space from the beginning or end. The white space in middle will be unchanged.
Let's take an example where user enter some text input in the text area which can contain white space and user can remove white space by clicking a button using jQuery.
In above example, we have created text area and given some default values 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.
Conclusion
In this article, we have taken a practical example of 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.