Skip to content

Instantly share code, notes, and snippets.

@yuchi
Created July 24, 2014 21:39
Show Gist options
  • Save yuchi/b017a592f647f50f8d35 to your computer and use it in GitHub Desktop.
Save yuchi/b017a592f647f50f8d35 to your computer and use it in GitHub Desktop.
CamelCaseUtil.normalizeCamelCase in JS
function isUpperCase(c) {
return (c !== c.toLowerCase());
}
function normalize(s) {
var buffer = '';
var upperCase = false;
var l = s.length;
var c, nextUpperCase;
for (var i = 0; i < s.length; ++i) {
c = s.charAt(i);
if (i < (l - 1)) {
nextUpperCase = isUpperCase(s.charAt(i + 1));
}
if ((i > 0) && isUpperCase(c)) {
if (upperCase && nextUpperCase) {
c = c.toLowerCase();
}
upperCase = true;
}
else {
upperCase = false;
}
buffer += c;
}
return buffer;
}
console.dir([
'inputOVPs',
'inputOVPS',
'somethingURL',
'somethingURLs'
].reduce(function (memo, s) {
memo[ s ] = normalize(s);
return memo;
}, {}));
/*
outputs
{ inputOVPs: 'inputOvPs',
inputOVPS: 'inputOvps',
somethingURL: 'somethingUrl',
somethingURLs: 'somethingUrLs' }
*/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment