Skip to content

Instantly share code, notes, and snippets.

@assertchris
Created June 2, 2010 15:02
Show Gist options
  • Save assertchris/422472 to your computer and use it in GitHub Desktop.
Save assertchris/422472 to your computer and use it in GitHub Desktop.
Optimized JavaScript string trim
function trim(str)
{
// immediate return!
if(!str)return '';
// markers
var modified = false, start = -1, end = str.length;
// traverse from beginning and from end for markers...
while(str.charCodeAt(--end) < 33 || str.charCodeAt(end) == 65279) modified = true;
while(str.charCodeAt(++start) < 33 || str.charCodeAt(start) == 65279) modified = true;
// return slice only if modified
return modified ? str.slice(start, end + 1) : str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment