As developers, we constantly need to reformat text strings for variables, database keys, or file names. I was tired of writing temporary regex scripts in my console every time I needed to change formats, so I built a clean, client-side Case Converter.
The Approach
I built this using 100% Vanilla JS. It handles the formatting entirely in the browser, providing instant, real-time conversion as you type.
Here is a quick look at the core logic handling the conversion to camelCase and snake_case:
function toCamelCase(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
return index === 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
}
function toSnakeCase(str) {
return str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('_');
}
Try it out
You can use the live tool for free here: Case Converter
Let me know what you think or if you'd add any other obscure casing formats in the comments!
Top comments (1)
Might want to revisit the 'title case' one... there's no universal standard, but just capitalising each word is far from correct.
Title case or headline case is a style of capitalization used for rendering the titles of published works or works of art in English. When using title case, all words are capitalized, except for minor words that are not the first or last word of the title. There are different rules for which words are major, hence capitalized. As an example, a headline might be written: "The Quick Brown Fox Jumps over the Lazy Dog".