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.
π§ The Problem
We want to convert this:
"camelCaseExample"
Into this:
"camel_case_example"
Without using .replace() or regular expressions.
π« The Regex Way (Just for Comparison)
function camelToSnake(str) { return str.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase(); }
Great, but regex has downsides:
- Black-box behavior
- Poor readability
- Harder to debug
- Slower on large strings
Let's throw it out and do it manually.
β The Loop-Based Approach
function camelToSnake(str) { let result = ''; for (let char of str) { if (char >= 'A' && char <= 'Z') { result += '_' + char.toLowerCase(); } else { result += char; } } return result; }
π§ͺ Example:
camelToSnake("camelCaseExample"); // "camel_case_example" camelToSnake("getHTTPResponseCode"); // "get_h_t_t_p_response_code"
π€ What About Acronyms?
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; }
π Behavior:
camelToSnakeSmart("getHTTPResponseCode"); // "get_http_response_code"
We only insert underscores between lowercaseβuppercase transitions, preserving acronyms.
π‘ Why This Matters
- β Readable: Anyone can follow the logic.
- π Fast: No pattern engine overhead.
- π§© Customizable: Want kebab-case? Just tweak one line.
- π οΈ Debuggable: Step through with a debugger, no black magic.
π Bonus: From snake_case to camelCase?
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"
π Closing Thoughts
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