Skip to content

Instantly share code, notes, and snippets.

@mattwiebe
Created June 3, 2011 05:27
Show Gist options
  • Save mattwiebe/1005915 to your computer and use it in GitHub Desktop.
Save mattwiebe/1005915 to your computer and use it in GitHub Desktop.
unCamelCase.js
/**
* Turns someCrazyName into Some Crazy Name
* Decent job of acroynyms:
* ABCAcryonym => ABC Acryoynm
* xmlHTTPRequest => Xml HTTP Request
*/
String.prototype.unCamelCase = function(){
return this
// insert a space between lower & upper
.replace(/([a-z])([A-Z])/g, '$1 $2')
// space before last upper in a sequence followed by lower
.replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
}
// Or, one liner.
String.prototype.unCamelCase=function(){return this.replace(/([a-z])([A-Z])/g,'$1 $2').replace(/\b([A-Z]+)([A-Z])([a-z])/,'$1 $2$3').replace(/^./,function(s){return s.toUpperCase();})}
@activedecay
Copy link

minor update to handle one digit after a v, which is common for my use case

  return value
    // insert a space between lower & upper
    .replace(/([a-z])([A-Z])/g, '$1 $2')
    .replace(/([0-9])([A-Z])/g, '$1 $2') // IPv4Addresses => IPv4 Addresses
    // space before last upper in a sequence followed by lower
    .replace(/\b([A-Z]+)([A-Z])([a-z][^0-9])/, '$1 $2$3') // // IPv4 Addresses != I Pv4 Addresses
    .replace(/\bId\b/, "ID")
    // uppercase the first character
    .replace(/^./, function(str){ return str.toUpperCase(); })
    // uppercase all the space lowercase chars
    .replace(/ ([a-z])/g, function(str){ return str.toUpperCase(); })

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