Skip to content

Instantly share code, notes, and snippets.

@eliperelman
Forked from 140bytes/LICENSE.txt
Created June 20, 2011 16:53
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save eliperelman/1035982 to your computer and use it in GitHub Desktop.
Save eliperelman/1035982 to your computer and use it in GitHub Desktop.
String.prototype.trim polyfill for 140byt.es

String.prototype.trim polyfill for 140byt.es

Adds the trim method to strings in versions of JavaScript that do not natively support it.

''.trim || (String.prototype.trim = // Use the native method if available, otherwise define a polyfill:
function () { // trim returns a new string (which replace supports)
return this.replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g,'') // trim the left and right sides of the string
})
''.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g,'')})
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Eli Perelman http://eliperelman.com
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "StringPrototypeTrimPolyfill",
"description": "Adds the trim method to strings in versions of JavaScript that do not natively support it.",
"keywords": [
"string",
"prototype",
"trim",
"polyfill",
"ecmascript5"
]
}
<!DOCTYPE html>
<title>String.prototype.trim polyfill</title>
<script>
''.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g,'')})
// logs 'my awesome string'
console.log(' my awesome string '.trim());
</script>
@jdalton
Copy link

jdalton commented Aug 21, 2011

The whitespace included in the character class \s is inconsistent across browsers. Instead a manual check of the required whitespace - is - best.
Also browsers like Chrome have a bug where String.prototype.trim = ''.trim will cause String#trim to become enumerable.

@eliperelman
Copy link
Author

Fixing the enumerable issue. I'm not sure yet if I can tackle making it any more robust as the character class alone to resolve the whitespace issue looks to be over 140 characters. I will research.

@eliperelman
Copy link
Author

subzey commented in another gist of mine that the following regex might work: ^[\s\uFEFF]+|[\s\uFEFF]+$. I will use it unless you think there is something non-compliant with it.

@chrisjacob
Copy link

Did you happen to find any issues with the regex you implemented?

@ivomarsan
Copy link

return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment