In web development, displaying content on a webpage can be dynamically generated. Thus, there can be a human error like extra space or a tab or a new line is added by mistake. However, displaying the same data as input can be bad for the user experience. For situations like this, we have to remove white space from the content before showing it or before adding to 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 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. The white space in the middle will be unchanged.
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.