But there are some notable differences in their working principle, which we will discover in our example sets. Let’s hop in!
$.trim(str) to Trim a String in jQuery
.trim() was introduced, the jQuery function lost its sole purpose of performing the task of trimming.
In jQuery release
str.trim() method was encouraged. We will have an HTML body with two paragraph tags in our example.
One will take the trimmed value, and the other will take the original message.
As we all know, HTML, by default, works on undefined spaces before and after any paragraph. So it can be unrecognizable if the
$.trim(str) function performs its job.
We will calculate the strings’ length before and after and add them along with the message we pass. Let’s jump to the code fence.
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <p id="text"></p> <p id = "val"></p> <script> var str = "\n jQuery trimming \n\n"; $( "#text" ).html("Trimmed: " + $.trim(str) + $.trim(str).length); $( "#val" ).html("Original: " + str + str.length); </script>
We see here the trimmed message has a length of 15 after excluding the extra spaces. But if you notice the original print of the string, there is a certain gap between the length count and the string.
This defines some spacing issues but doesn’t explicitly portray how many spaces, and line break exists.
But successively, the length of the original message has been counted; we know that initially, there was a 3 gap and 1 line break before the string started. Also, in the rear portion of the string, there was 2 line break and 8 white spaces.
While the original message only has valid 15 characters, and the HTML body fails to show the meaningless gaps.
String.trim() Method to Trim Strings
str.trim() methods respond to a similar output pattern. In the example, we will take a string and perform the method.
var str = " Cut it off "; console.log($.trim(str)); console.log(str.trim()); console.log(str);
str, and the jQuery function takes the
str.trim() method does not take any arguments, whereas the
$.trim(str) takes the
str as a parameter.