Emmanuel Akinfulubi

JavaScriptString

Convert camelCase to snake_case in JavaScript

Intermediate · 3 min read

JavaScript names things in camelCase, like totalPrice. Databases often want snake_case, total_price, and web addresses and CSS classes prefer kebab-case, total-price. When you send data from JavaScript to one of those places, you need to convert the names the other way.

In this tutorial you will write toSnake and toKebab, which turn 'totalPrice' into 'total_price' and 'total-price'. You will handle a name that starts with a capital, and see what happens to a short form in capitals like ID. You should know toLowerCase and have used replace. The regex pieces are explained below.

The idea

In camelCase, every capital letter marks the start of a new word. So the plan is:

  1. Find every capital letter.
  2. Put a separator in front of it, and make it lower case.

totalPrice → total + _p + rice → total_price.

The regex pieces

A regular expression, or regex, is a pattern for text, written between slashes. Two small patterns cover this exercise:

  • /[A-Z]/g: [A-Z] matches one capital letter from A to Z, and g means "every match".
  • /^_/: ^ means "the very start of the text", so this matches an underscore only if it is the first character.

replace can take a function as its second argument. For each match, it calls the function with the matched text and uses whatever the function returns.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

17 camelCase back to snake_case and kebab-case

fair

Convert 'totalPrice' to 'total_price' and 'total-price'. Handle a leading capital, and see what happens to an acronym.

Stuck? Three hints, smallest first
  1. 1. Replace each capital with a separator plus its lower-case form.
  2. 2. A leading capital would produce a stray separator at the front, so strip it.
  3. 3. An acronym is a run of capitals, and each one gets its own separator.

Step 1: separator plus lower case

Step 1

const result = 'totalPrice'.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase());
console.log(result); // 'total_price'

The only capital is P. The function turns it into _p, and replace puts that in its place.

Step 2: a name that starts with a capital

Class names and some keys start with a capital: TotalPrice. Try the same code:

Step 2

const result = 'TotalPrice'.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase());
console.log(result); // '_total_price'

The first T also gets a separator in front, so the result starts with a stray underscore. That is why the answer adds a second replace to strip an underscore at the very start.

Step 2

const toSnake = (text) =>
  text.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase()).replace(/^_/, '');
console.log(toSnake('TotalPrice')); // 'total_price'
console.log(toSnake('totalPrice')); // 'total_price'

The two replace calls are chained: the second one works on the result of the first.

Step 3: kebab-case for free

kebab-case is the same thing with dashes. Rather than repeat the logic, build it on top of toSnake:

Step 3

const toSnake = (text) =>
  text.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase()).replace(/^_/, '');
const toKebab = (text) => toSnake(text).replace(/_/g, '-');
console.log(toKebab('totalPrice'));          // 'total-price'
console.log(toKebab('shippingAddressLine')); // 'shipping-address-line'

/_/g matches every underscore, and each one is swapped for a dash.

Step 4: the easy inputs

Step 4

const toSnake = (text) =>
  text.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase()).replace(/^_/, '');
console.log(toSnake('price'));              // 'price'
console.log(JSON.stringify(toSnake('')));   // "", an empty string
console.log(toSnake('line1Total'));         // 'line1_total'

No capitals, nothing to change. Digits aren't in [A-Z], so they stay where they are.

Step 5: a short form in capitals

Now an awkward one. Many names contain a short form written in capitals, like ID or URL. This is called an acronym.

Step 5

const toSnake = (text) =>
  text.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase()).replace(/^_/, '');
console.log(toSnake('orderID')); // 'order_i_d'

Each capital gets its own separator, so ID falls apart into i_d. Most people would want order_id. Whether this matters depends on your data. Fixing it means treating a run of capitals as one word, which needs a more careful pattern than one [A-Z].

Step 6: convert back again

A good test of two converters is a round trip: convert one way, then back, and check you get the original. Here is the camelCase converter from the last exercise, without the toLowerCase() that flattened existing capitals:

Step 6

const toSnake = (text) =>
  text.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase()).replace(/^_/, '');
const toCamel = (text) => text.replace(/[-_](.)/g, (_, c) => c.toUpperCase());
console.log(toCamel(toSnake('totalPrice'))); // 'totalPrice'
console.log(toCamel(toSnake('orderID')));    // 'orderID'

The round trip works, even for the acronym. toCamel turns each _i and _d back into a capital, so order_i_d returns to orderID. That is luck rather than design: nobody would write order_i_d on purpose.

The full solution

Here is the complete answer: toSnake, toKebab, and toCamel for the round trip, with the acronym case printed. Press Run to see each conversion.

The answer

const toSnake = (text) =>
  text.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase()).replace(/^_/, '');

const toKebab = (text) => toSnake(text).replace(/_/g, '-');

// The reverse direction, without the lower-casing that exercise 16 warned about.
const toCamel = (text) => text.replace(/[-_](.)/g, (_, c) => c.toUpperCase());

console.log("toSnake('totalPrice')  :", toSnake('totalPrice'));
console.log("toKebab('totalPrice')  :", toKebab('totalPrice'));
console.log("toSnake('TotalPrice')  :", toSnake('TotalPrice'), '<- the leading _ was stripped');
console.log("toSnake('orderID')     :", toSnake('orderID'), '<- each capital gets its own separator');

Output


      
10 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('camelCase becomes snake_case', toSnake('totalPrice'), 'total_price');
test('and kebab-case', toKebab('totalPrice'), 'total-price');
test('a leading capital would leave a stray separator, so it is stripped', toSnake('TotalPrice'), 'total_price');
test('a single word is unchanged', toSnake('price'), 'price');
test('the empty string stays empty', toSnake(''), '');
test('an acronym is split letter by letter, which is rarely wanted', toSnake('orderID'), 'order_i_d');
test('three words come out cleanly', toKebab('shippingAddressLine'), 'shipping-address-line');
test('digits stay where they are', toSnake('line1Total'), 'line1_total');
test('the round trip back to camelCase works', toCamel(toSnake('totalPrice')), 'totalPrice');
test('and it even survives the ugly acronym', toCamel(toSnake('orderID')), 'orderID');

'orderID' becoming 'order_i_d' is the case that decides whether this function is good enough for your data. Fixing it means treating a run of capitals as one unit and deciding where the next word starts, which needs a lookahead: /([A-Z]+)([A-Z][a-z])/ to split 'HTTPServer', then /([a-z0-9])([A-Z])/ for the ordinary case.

The round trip surviving the acronym is a small piece of luck worth noticing: toCamel puts each separated letter back as a capital, so 'order_i_d' returns to 'orderID' even though nobody would have written that intermediate form on purpose.

Common mistakes

  • Forgetting the leading separator. 'TotalPrice' becomes '_total_price' unless you strip the first underscore.
  • Leaving off the g flag. Only the first capital is converted, so 'shippingAddressLine' becomes 'shipping_addressLine'.
  • Assuming acronyms come out whole. orderID becomes order_i_d. Check your real names before trusting the output.

Try it yourself

  1. Write toConstant(text) that turns 'totalPrice' into 'TOTAL_PRICE'.
  2. Convert every key of { firstName: 'Ada', lastName: 'Lovelace' } to snake_case. (Hint: Object.entries and Object.fromEntries.)
  3. Try toKebab('HTMLParser') and explain the result.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.