DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Javascript Trim

09.13.2007
| 9757 views |
  • submit to reddit
        
// Removes leading and ending whitespaces, nbsps
function trim(str) {
    return str.replace(/(^[\s\xA0]+|[\s\xA0]+$)/g, '');
}
    

Comments

Steven Levithan replied on Wed, 2008/01/30 - 1:58am

According to ECMA-262v3, the \x0a (no-break space) character is included in \s. Also, the parens are unnecessary here. See this post for a comparison of a variety of JS trim functions: trim javascript.