Created
June 2, 2010 15:02
-
-
Save assertchris/422472 to your computer and use it in GitHub Desktop.
Optimized JavaScript string trim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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