We are rebuilding. Join us.

We are rebuilding our site—live at building.seesparkbox.com. Join us, real-time, as the site evolves. It will be ugly at times. Sometimes it will be downright broken. But it will always be transparent and real. You can even check under the hood of the public repo on Github and share your ideas. Crazy, are we? Read why we're doing this.

Let’s be more than friends.

We really
like to share

The Foundry is our place to share articles, tutorials, events, and more. Search for a topic or just read everything.

Duck Punching jQuery’s Trim Method

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.

Keep up with new posts in the Foundry by subscribing to our weekly email: The Spark.