Last Updated: February 25, 2016
·
1.237K
· philfreo

Patch String.prototype.trim() to work in all browsers.

It's nice to be able to call " foo ".trim() to get "foo", but this doesn't work in older browsers. Here's a shim so that it does.

// Patch trim function
if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g,'');
    };
}

(If you are against overriding String.prototype, you can always use $.trim().)

2 Responses
Add your response

You chose a slow implentation, use a faster one:
http://blog.stevenlevithan.com/archives/faster-trim-javascript

over 1 year ago ·

Cool, thanks for sharing. In my case though this is never getting called in a loop so the difference is meaningless.

over 1 year ago ·