Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between $.trim and trim?

I have this simple example below which uses trim. As per the title of the question, is there any difference between them?. As you can see below they have the same output. If the answer is "No", which one is much better to use?

Currently I use .trim() because it's my first time seeing $.trim().

var SampleTrim = '     TRIM         ';

console.log(SampleTrim.trim());
console.log($.trim(SampleTrim));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 918
KiRa Avatar asked Mar 31 '17 02:03

KiRa


2 Answers

String.prototype.trim is not available below IE9, otherwise they are the same.

The recommended String.prototype.trim polyfill on MDN is exactly the same as that used in jQuery source.

In most cases, the native implementation would be faster to use. This JSPerf by Sumit Gulati suggests that too.

Realistically, the difference in performance would be quite negligible and I wouldn't base my decision on performance. However, it would be better to use the native implementation so that there's no dependency on jQuery. The large websites have dropped support for IE8 and I think it's safe to follow suit (:

like image 70
Yangshun Tay Avatar answered Nov 03 '22 05:11

Yangshun Tay


jQuery's trim() function was available long before JavaScript's native trim() function was added, which is available in browsers above IE9 and the like.

Use the native trim function for future projects.

like image 2
Drewby Avatar answered Nov 03 '22 05:11

Drewby