Convert snake_case and kebab-case to camelCase in JavaScript
Intermediate · 4 min read
Different parts of a program like to name things differently. A database column might be total_price, a web address or CSS class total-price, and a JavaScript variable totalPrice. When data moves between them, you need to convert the names, and the most common conversion is into JavaScript's style.
In this tutorial you will write one function, toCamel, that turns both 'total_price' and 'total-price' into 'totalPrice'. Then you will find three inputs it gets wrong, and learn why. You should know toUpperCase and toLowerCase. Regular expressions are explained below from the start.
The three naming styles
- snake_case: words in lower case joined by underscores, like a snake on the ground:
total_price. - kebab-case: words joined by dashes, like pieces on a skewer:
total-price. - camelCase: no separators; every word after the first starts with a capital, like the humps of a camel:
totalPrice.
To go from the first two to camelCase, you find each separator, remove it, and capitalize the letter right after it.
A regex for "separator plus the next character"
A regular expression, or regex, is a pattern for text, written between slashes. The one we need is:
/[-_](.)/g
[-_]means one character that is either a dash or an underscore..means any one character. Wrapping it in round brackets makes it a capture group: a part of the match you get back on its own.gat the end means "every match", not just the first.
So in total_price, this pattern matches _p, and the group is p.
Here is the exercise. Have a go on your own first, or read on and we will build it step by step.
16 snake_case and kebab-case into camelCase
fairConvert 'total_price' and 'total-price' to 'totalPrice' with one function. Then find the three inputs it gets wrong.
Stuck? Three hints, smallest first
- 1. Match the separator together with the character after it, and upper-case that character.
- 2. A replacement function receives the capture groups as extra arguments.
- 3. Lower-casing the whole string first handles SHOUTING_SNAKE — and destroys anything already camelCased.
Step 1: replace with a function
replace can take a function instead of replacement text. For each match, it calls your function and uses what it returns. The function receives the whole match first, then each capture group.
const result = 'total_price'.replace(/[-_](.)/g, (whole, c) => {
console.log(whole, c); // _p p
return c.toUpperCase();
});
console.log(result); // 'totalPrice'
The whole match _p is swapped for P, so the underscore disappears and the letter becomes a capital. That is the entire conversion.
Step 2: make it a function
You don't need the whole match, only the group. A common way to say "I'm ignoring this argument" is to name it _.
const toCamel = (text) =>
text.toLowerCase().replace(/[-_](.)/g, (_, c) => c.toUpperCase());
console.log(toCamel('total_price')); // 'totalPrice'
console.log(toCamel('total-price')); // 'totalPrice'
console.log(toCamel('a_b_c')); // 'aBC'
console.log(toCamel('order-id')); // 'orderId'
Both separators work because [-_] accepts either one. The toLowerCase() at the front is there for the next step.
Step 3: shouting snake case
Constants are often written in capitals: TOTAL_PRICE. Lower-casing first makes those work too.
const toCamel = (text) =>
text.toLowerCase().replace(/[-_](.)/g, (_, c) => c.toUpperCase());
console.log(toCamel('TOTAL_PRICE')); // 'totalPrice'
console.log(toCamel('price')); // 'price'
console.log(JSON.stringify(toCamel(''))); // "", an empty string
A word with no separator, and the empty string, pass through unchanged. Now for the three inputs it gets wrong.
Step 4: a separator at the end
const toCamel = (text) =>
text.toLowerCase().replace(/[-_](.)/g, (_, c) => c.toUpperCase());
console.log(toCamel('price_')); // 'price_'
The pattern needs a character after the separator. At the end of the string there is none, so nothing matches and the underscore stays.
Step 5: two separators in a row
const toCamel = (text) =>
text.toLowerCase().replace(/[-_](.)/g, (_, c) => c.toUpperCase());
console.log(toCamel('a__b')); // 'a_b'
The pattern matches the first underscore plus "the next character", which is the second underscore. Upper-casing an underscore does nothing, so it comes back as _, and the b is never capitalized. Changing the pattern to /[-_]+(.)/g, where + means "one or more", treats a run of separators as one and fixes this.
Step 6: input that is already camelCase
const toCamel = (text) =>
text.toLowerCase().replace(/[-_](.)/g, (_, c) => c.toUpperCase());
console.log(toCamel('totalPrice')); // 'totalprice'
This is the serious one. The toLowerCase() that rescued TOTAL_PRICE also flattens the capital in totalPrice, and there is no separator left to bring it back. The function only works safely when you know the input is snake or kebab case. If it might already be camelCase, drop the toLowerCase() and handle capitals some other way.
The full solution
Here is the complete answer: toCamel, the inputs it handles, and the three it gets wrong, printed with notes. Press Run and read the lines under "the three it gets wrong".
const toCamel = (text) =>
text.toLowerCase().replace(/[-_](.)/g, (_, c) => c.toUpperCase());
console.log("toCamel('total_price') :", toCamel('total_price'));
console.log("toCamel('TOTAL_PRICE') :", toCamel('TOTAL_PRICE'));
console.log('--- the three it gets wrong ---');
console.log("toCamel('price_') :", toCamel('price_'), '<- nothing follows, so the separator stays');
console.log("toCamel('a__b') :", toCamel('a__b'), '<- only one separator is consumed');
console.log("toCamel('totalPrice') :", toCamel('totalPrice'), '<- already camelCase, and now flattened');
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.
test('snake_case becomes camelCase', toCamel('total_price'), 'totalPrice');
test('kebab-case does too', toCamel('total-price'), 'totalPrice');
test('several words in a row', toCamel('a_b_c'), 'aBC');
test('SHOUTING_SNAKE works because of the lower-casing', toCamel('TOTAL_PRICE'), 'totalPrice');
test('a word with no separator is unchanged', toCamel('price'), 'price');
test('the empty string stays empty', toCamel(''), '');
test('a trailing separator has nothing to promote, so it survives', toCamel('price_'), 'price_');
test('a doubled separator only loses one of the two', toCamel('a__b'), 'a_b');
test('and lower-casing first DESTROYS input that was already camelCase', toCamel('totalPrice'), 'totalprice');
test('so only convert when you know what shape the input is in', toCamel('order-id'), 'orderId');
The toLowerCase() at the front is doing two jobs and only one of them is wanted. It makes 'TOTAL_PRICE' work, and it flattens 'totalPrice' to 'totalprice'. If your input might already be camelCase, drop it and handle the shouting case separately.
'a__b' is the honest limitation: [-_](.) consumes one separator and the character after it, so the second underscore is just "the character after it" and gets upper-cased into itself. Matching [-_]+(.) instead fixes that one.
Common mistakes
- Running the conversion twice. The second pass lower-cases the result of the first, so
totalPricebecomestotalprice. - Writing the replacement as a string, like
'$1'.toUpperCase(). That upper-cases the text'$1'beforereplaceever sees it, so nothing gets capitalized. Use a function. - Forgetting the
gflag. Without it only the first separator is replaced:'a_b_c'becomes'aB_c'.
Try it yourself
- Change the pattern to
/[-_]+(.)/gand check that'a__b'now gives'aB'. - Write
toPascal(text), which also capitalizes the first letter:'total_price'becomes'TotalPrice'. - Make the function accept spaces as separators too, so
'total price'works.