EDIT : Now works in IE8 unchanged.
EDIT . I was in the minority about what camelCase (leading character in lowercase and uppercase) is actually. The community as a whole believes that the leading lowercase is the case of a camel, and the leading capital is pascal. I created two functions that use only regex patterns. :) So, we use a single dictionary, which I changed to fit most.
All that seems necessary to me is one regular expression anyway:
var camel = " THIS is camel case " camel = $.trim(camel) .replace(/[^A-Za-z]/g,' ') .replace(/(.)/g, function(a, l) { return l.toLowerCase(); }) .replace(/(\s.)/g, function(a, l) { return l.toUpperCase(); }) .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
or
var pascal = " this IS pascal case " pascal = $.trim(pascal) .replace(/[^A-Za-z]/g,' ') .replace(/(.)/g, function(a, l) { return l.toLowerCase(); }) .replace(/(^.|\s.)/g, function(a, l) { return l.toUpperCase(); }) .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
In functions: you will notice that in these functions the replacement replaces any non -zz with a space vs an empty string. This is done to create word boundaries for capitalization. "hello-MY # world" → "HelloMyWorld"
// remove \u00C0-\u00ff] if you do not want the extended letters like é function toCamelCase(str) { var retVal = ''; retVal = $.trim(str) .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */ .replace(/(.)/g, function (a, l) { return l.toLowerCase(); }) .replace(/(\s.)/g, function (a, l) { return l.toUpperCase(); }) .replace(/[^A-Za-z\u00C0-\u00ff]/g, ''); return retVal } function toPascalCase(str) { var retVal = ''; retVal = $.trim(str) .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */ .replace(/(.)/g, function (a, l) { return l.toLowerCase(); }) .replace(/(^.|\s.)/g, function (a, l) { return l.toUpperCase(); }) .replace(/[^A-Za-z\u00C0-\u00ff]/g, ''); return retVal }
Notes:
- I left A-Za-z against adding a case insensitive flag (i) to the pattern (/ [^ AZ] / ig) for readability.
- This works in IE8 (srsly, which uses IE8 more.) Using the (F12) dev tools I tested in IE11, IE10, IE9, IE8, IE7 and IE5. It works in all document modes.
- This will be true in the case of the first letter of lines starting with or without spaces.
Enjoy