Last updated on
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!
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'
var someText = ' I love trimming strings '; var trimmedText = someText.trim(); // Gives, 'I love trimming strings'
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.
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
So there’s no massive performance gain to be had by not using jQuery trim.
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.