Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DBJDBJ/329172 to your computer and use it in GitHub Desktop.
Save DBJDBJ/329172 to your computer and use it in GitHub Desktop.
Use native String.prototype.trim function wherever possible. Do not use String.trim. It is not part of ES5. Browsers are not required to implement it.
// dbjdbj@gmail.com
// Inspired also by http://github.com/dieseltravis
(function () {
var trimLeft = /^\s+/, trimRight = /\s+$/;
// Verify that \s matches non-breaking spaces (IE fails on this test)
if ( !/\s/.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// Use native String.prototype.trim function wherever possible
// Do not use String.trim. It is not part of ES5
window.dbj_trim = "function" === typeof "".trim ? function( text ) {
return ! text ? "" : String.prototype.trim.call( text.toString() );
} :
// Otherwise use our own trimming functionality
function( text ) {
return ! text ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment