jQuery trim function: How to remove whitespace from a string

Learn how to use the jQuery trim function.

If you want to remove whitespace from a string then the jQuery trim function will do just that for you. By whitespace I mean spaces (or tabs) at the start or end of your string. If you’re using ES6 template literals that spread over several lines, it will strip those too! Unlike other things in jQuery (like jQuery if statement and jQuery substr) this is an actual jQuery function. This is however based on an existing JavaScript trim function.

Using the jQuery trim function

If you’re keen to just see the syntax, here’s an example of using the jQuery trim function.

var someText = '  I love trimming strings    ';
var trimmedText = $.trim(someText); // Gives, 'I love trimming strings'

If your confused how this is different from the native JavaScript trim function (there isn’t any difference in the way it works to be honest) then here’s the same example without using jQuery.

var someText = '  I love trimming strings    ';
var trimmedText = someText.trim(); // Gives, 'I love trimming strings'

Notice how the native JavaScript version is a function that is called on the actual string itself

When to use the jQuery trim function

So what’s the difference between the two? Well, there is none. The only time you could arguably use the jQuery function over the native version is perhaps to fit with your particular project’s style guide. In other words, the whole project you are working on uses jQuery heavily therefore it makes sense to make the code jQueryfied (new word just invented) so developers don’t get confused when to use native JavaScript and when to use jQuery. What about performance? I set up a quick performance check to see which function performed better: https://jsperf.com/does-jquery-trim-perform-worse-than-just-trim jQuery trim performance Unsurprisingly, the native JavaScript one is faster but only just - about 0.88% faster in Chrome and about 3.49% faster in Edge (let me know if you find different results in any browsers). So there’s no massive performance gain to be had by not using jQuery trim.

Conclusion

It seems like a strange addition to add the jQuery trim function to the library but it works fine and has no massive performance implications. Of course, you just need to remember which way round to use it. Put the string inside the parentheses if using jQuery and call the function directly on the string if using native JavaScript.