How to convert "camelCase" to "Camel Case"?
For a super-fast way to convert camelCase
to Camel Case
, here's some nifty JavaScript code:
So, what's happening here? We're using JavaScript's replace
method and regular expressions (regex) to insert a space at each transition from lowercase to uppercase (camel bump 😉), then capitalizing the first letter. Simple, right?
Enhancements for edge cases
Let's say your camelCase
is not in the pettiest form or you've some wild ones like 'CSVFiles' or 'loadXMLHttpRequest'. Our function needs to handle these rare species as well:
Understanding the magic
Look at this regex sorcery as a versatile tool tackling consecutive uppercase letters ([A-Z]+
) and selective spacing (avoiding extra spaces at the start or between the sequences). This results in preserving acronyms and initialisms in the original string.
Bringing it all together
Camel riding through special sequences
For advanced scenarios with acronyms or initialisms within camel case, like 'parseURLAndRedirect', an enhanced function does the trick:
Liberating camels with Lodash
Standard JavaScript not spicy enough? Lodash got your back. Its startCase
function handles the conversion like a champ:
Or even chain different methods together for a coding spectacle:
Interactive camel conversion
For a real-time ASCII art... err... 🐫conversion as the user types, use the input
event:
Was this article helpful?