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()
.)
Written by Phil Freo
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Strings
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#