Skip to content

Instantly share code, notes, and snippets.

@dwcullop
Last active July 2, 2016 00:04
Show Gist options
  • Save dwcullop/66d936cfc447e0a223558e0637fb4739 to your computer and use it in GitHub Desktop.
Save dwcullop/66d936cfc447e0a223558e0637fb4739 to your computer and use it in GitHub Desktop.
Function for converting camelCase and/or PascalCase strings into a string with normal spacing and a function to test it. If you find a case where it doesn't work, please add it to the comments.
function fixCamelCase( str )
{
return str.replace( /(?!^)(\S)?([A-Z][a-z])/, ( m, a, b ) => a ? a + " " + b : m )
.replace( /(?:^|\s)[a-z]/g, m => m.toUpperCase() )
.replace( /(?:[a-z][A-Z]|\D\d)/g, m => m[0] + " " + m[1] );
}
(function()
{
var tests =
{
"HDD": "HDD",
"GeneralInvestigation": "General Investigation",
"Fan": "Fan",
"ExchangeSVCS": "Exchange SVCS",
"BlahIT": "Blah IT",
"OSSystem": "OS System",
"ioVariance": "Io Variance",
"TP50": "TP 50",
"TP:50": "TP: 50",
"Hello There": "Hello There",
"hello there": "Hello There",
"XmlHTTPResponse": "Xml HTTP Response",
"Hello there": "Hello There"
};
function runTest( key )
{
if ( fixCamelCase(key) != tests[key] )
{
console.error( "Failed [", key, "] Result: [", fixCamelCase(key), "] Expected: [", tests[key], "]" );
}
}
Object.keys(tests).forEach( key => runTest(key) );
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment