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

String.prototype.swapcase

09.29.2005
| 7013 views |
  • submit to reddit
        
String.prototype.swapcase = function(){
	return this.replace(/([a-z])|([A-Z])/g,function($0,$1,$2){
		return ($1) ? $0.toUpperCase() : $0.toLowerCase()
	})
}

"abcdeABCDE".swapcase() => ABCDEabcde    

Comments

Snippets Manager replied on Fri, 2007/01/05 - 1:38am

The snipplet is slow: 10 000 times on IE6 890ms. 10 000 times on FF3 600ms. Do it much more faster with: String.prototype.swapcase = function(){ return this.replace(/([a-z]+)|([A-Z]+)/g,function($0,$1,$2){ return ($1) ? $0.toUpperCase() : $0.toLowerCase(); }) } 10 000 times on IE6 344ms. 10 000 times on FF3 166ms.