In the world of code conventions, case styles are more than aesthetics β they're contracts. JavaScript favors camelCase, while many APIs, databases, and configuration files lean on snake_case. Converting between them is a common task β and yes, regex is usually the weapon of choice. But what if you want clarity, control, or speed, and no regex?
Let's walk through an elegant, loop-based solution.
We want to convert this:
"camelCaseExample"
Into this:
"camel_case_example"
Without using .replace() or regular expressions.
function camelToSnake(str) { return str.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase(); }
Great, but regex has downsides:
Let's throw it out and do it manually.
function camelToSnake(str) { let result = ''; for (let char of str) { if (char >= 'A' && char <= 'Z') { result += '_' + char.toLowerCase(); } else { result += char; } } return result; }
camelToSnake("camelCaseExample"); // "camel_case_example" camelToSnake("getHTTPResponseCode"); // "get_h_t_t_p_response_code"
That naive version splits every uppercase letter β which can shred acronyms into noise.
Let's fix that with a smarter variant:
function camelToSnakeSmart(str) { let result = ''; for (let i = 0; i < str.length; i++) { const char = str[i]; const isUpper = char >= 'A' && char <= 'Z'; const prevIsLower = i > 0 && str[i - 1] >= 'a' && str[i - 1] <= 'z'; if (isUpper && prevIsLower) { result += '_' + char.toLowerCase(); } else { result += char.toLowerCase(); } } return result; }
camelToSnakeSmart("getHTTPResponseCode"); // "get_http_response_code"
We only insert underscores between lowercaseβuppercase transitions, preserving acronyms.
Simple. Here's how:
function snakeToCamel(str) { return str.split('_').map((word, i) => i === 0 ? word : word[0].toUpperCase() + word.slice(1) ).join(''); }
snakeToCamel("get_http_response_code"); // "getHttpResponseCode"
Regex has its place, but for small transforms, explicit logic wins β it's more maintainable, more tunable, and often faster. Next time you're wrangling format conversions, consider reaching for clarity over cleverness.
Test your understanding with 3 quick questions