I was recently working on a project and needed to pull off the leading and trailing ‘/’ (if present) of a URL fragment. Since there’s no built-in trim method in Javascript, and the jQuery $.trim method only removes leading and trailing whitespace, I decided to punch a duck.
Duck punching is simply a method to add functionality to the language without actually modifying the language. Sure, you could just dig into the jQuery core files, and modify the trim method, but what do you do then when 1.5.1 becomes 1.5.2, or jumps to 1.6? If you modified the core files, you have to continue to modify the core every time you update it. If you make the change in your own file, by extending jQuery, your change will persist across jQuery updates.
So, I added this code at the top of my application.js file:
(function($) {
$.trim = function(str, replace) {
replace = replace || '\\s';
return str.replace(new RegExp('^' + replace + '*([\\S\\s]*?)' + replace + '*$'), '$1');
};
})(jQuery);
Line 1:
The start of an Immediately-Invoked Function Expression (IIFE).
Line 2:
Replace the jQuery trim method with this modified version.
Line 3:
If nothing was passed in to match, default to trimming whitespace. This will mimic the default behavior of $.trim().
Line 4:
Match str to the new regular expression, removing the replace variable from the beginning and end of str.
Consider the duck punched!
That’s it. You can now call jQuery’s trim method like this:
$.trim(' string to trim '); // result: 'string to trim'
$.trim('/portion/of/url/','\/') // result: 'portion/of/url'
Sounds like a duck, quacks like a duck, must be a duck.