Emmanuel Akinfulubi

JavaScriptBasic

Convert a sentence to camelCase in JavaScript

Intermediate · 3 min read

Programmers name things in a few standard styles. In camelCase, words are joined with no spaces and every word after the first starts with a capital: totalFareInKobo. In kebab-case, words are lowercase and joined with hyphens: total-fare-in-kobo. JavaScript variables usually use camelCase, and CSS class names and web addresses usually use kebab-case.

Converting between them comes up whenever data crosses from one world to another: a form label becomes an object key, a database column becomes a JavaScript property. In this tutorial you will write camel, which turns a sentence into camelCase, and kebab, which turns it back. You should know what strings, arrays, map and functions are.

The plan

To turn total fare in kobo into totalFareInKobo:

  1. Make everything lowercase.
  2. Split the text into words.
  3. Leave the first word alone, and capitalize the first letter of every other word.
  4. Join the words with nothing between them.

Capitalizing one word

w[0] is a word's first letter and w.slice(1) is everything after it. Uppercase the first part and stick them back together:

JavaScript

const w = 'fare';
console.log(w[0].toUpperCase() + w.slice(1)); // Fare

map gives you the position too

map passes two things to its function: the item, and its index, its position in the array starting from 0. That's how you can treat the first word differently:

JavaScript

console.log(['a', 'b', 'c'].map((w, i) => w + i)); // [ 'a0', 'b1', 'c2' ]

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

110 camelCase from a sentence

fair

Turn total fare in kobo into totalFareInKobo. Handle hyphens and underscores as separators too, cope with input that SHOUTS, and write the inverse that turns it back into total-fare-in-kobo.

Stuck? Three hints, smallest first
  1. 1. Lowercase everything first, then raise the first letter of every word except the first.
  2. 2. One split(/[\s_-]+/) handles spaces, underscores and hyphens together.
  3. 3. Going back is a replace on every capital letter.

Step 1: a first version

Step 1

function naiveCamel(text) {
  const words = String(text).trim().split(/\s+/).filter(Boolean);
  return words.map((w, i) => (i === 0 ? w : w[0].toUpperCase() + w.slice(1))).join('');
}
console.log(naiveCamel('total fare in kobo')); // totalFareInKobo

split(/\s+/) splits on any run of whitespace, and filter(Boolean) drops empty pieces. Inside map, the ? : (a ternary, a one-line if/else) keeps word 0 as it is and capitalizes the rest.

Step 2: shouted input breaks it

Form labels and spreadsheet headers are often in capitals or title case:

Step 2

function naiveCamel(text) {
  const words = String(text).trim().split(/\s+/).filter(Boolean);
  return words.map((w, i) => (i === 0 ? w : w[0].toUpperCase() + w.slice(1))).join('');
}
console.log(naiveCamel('TOTAL FARE')); // TOTALFARE
console.log(naiveCamel('Bus Stop'));   // BusStop

The code only ever raises letters. It never lowers the ones that were already capitals, so TOTAL FARE keeps its shout and Bus keeps its capital B. Neither result matches the key totalFare or busStop you'd look up later.

Step 3: lowercase first, and more separators

Step 3

function camel(text) {
  const words = String(text).trim().toLowerCase().split(/[\s_-]+/).filter(Boolean);
  return words.map((w, i) => (i === 0 ? w : w[0].toUpperCase() + w.slice(1))).join('');
}
console.log(camel('TOTAL FARE'));    // totalFare
console.log(camel('Bus Stop'));      // busStop
console.log(camel('bus-stop_name')); // busStopName

toLowerCase() flattens everything first, so the only capitals in the result are the ones map adds on purpose.

The pattern changed too. [\s_-] means "a whitespace character, an underscore or a hyphen", and the + means one or more of them in a row. Now the same function handles a form label (bus stop), a database column (bus_stop) and a CSS class (bus-stop).

Step 4: the edge cases

Step 4

function camel(text) {
  const words = String(text).trim().toLowerCase().split(/[\s_-]+/).filter(Boolean);
  return words.map((w, i) => (i === 0 ? w : w[0].toUpperCase() + w.slice(1))).join('');
}
console.log(camel('  two   words ')); // twoWords
console.log(camel('fare'));           // fare
console.log(camel('   ') === '');     // true

Extra spaces don't create empty words, a single word comes back unchanged, and empty input gives an empty string instead of an error.

Step 5: back to kebab-case

Going the other way means finding every capital letter and replacing it with a hyphen plus the lowercase letter:

Step 5

const kebab = (name) => name.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
console.log(kebab('totalFareInKobo')); // total-fare-in-kobo

/[A-Z]/g matches every capital letter A to Z. Because the second argument is a function, replace calls it for each match m and puts in whatever it returns.

This trip back isn't perfect. Every capital starts a new word, so an abbreviation falls apart:

JavaScript

const kebab = (name) => name.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
console.log(kebab('parseHTTPResponse')); // parse-h-t-t-p-response

Many style guides avoid the problem by writing abbreviations like ordinary words: parseHttpResponse.

The full solution

The answer panel has camel, the naiveCamel it replaces, and kebab. The checks cover the first word staying lowercase, hyphens and underscores, extra whitespace, one word, empty input, shouted input and the round trip back to kebab-case. Press Run to see the output.

The answer

function camel(text) {
  const words = String(text).trim().toLowerCase().split(/[\s_-]+/).filter(Boolean);
  return words.map((w, i) => (i === 0 ? w : w[0].toUpperCase() + w.slice(1))).join('');
}
// The same thing without the lowercasing, to show what it was for.
function naiveCamel(text) {
  const words = String(text).trim().split(/\s+/).filter(Boolean);
  return words.map((w, i) => (i === 0 ? w : w[0].toUpperCase() + w.slice(1))).join('');
}
const kebab = (name) => name.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
console.log(camel('total fare in kobo'), '|', kebab(camel('total fare in kobo')));
console.log('shouted input:', naiveCamel('TOTAL FARE'), 'vs', camel('TOTAL FARE'));

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a sentence becomes one identifier', camel('total fare in kobo'), 'totalFareInKobo');
test('the first word stays lowercase', camel('Bus Stop'), 'busStop');
test('hyphens and underscores are separators too', camel('bus-stop_name'), 'busStopName');
test('extra whitespace makes no empty words', camel('  two   words '), 'twoWords');
test('a single word is left alone', camel('fare'), 'fare');
test('empty text gives empty text', camel('   '), '');
test('shouted input needs the lowercasing', camel('TOTAL FARE'), 'totalFare');
test('without it, the shout survives', naiveCamel('TOTAL FARE'), 'TOTALFARE');
test('and kebab-case is the trip back', kebab(camel('total fare in kobo')), 'total-fare-in-kobo');

toLowerCase() before splitting is the line people leave out, and it only shows up on real input: a header of TOTAL FARE or a label of Bus Stop keeps letters that should have been flattened, so naiveCamel yields TOTALFARE and BusStop — neither of which matches the key you later look up. Lowercase first, then raise exactly the letters you intend to raise.

Treating spaces, underscores and hyphens as one class of separator means the same function converts a form label, a database column and a CSS class, which is where these conversions are actually used. The round trip is not quite lossless in general: kebab splits on every capital, so parseHTTPResponse becomes parse-h-t-t-p-response. Acronyms need a smarter pattern or a policy of not using them. Also exercise 24, which capitalised the first letter of each word for display; the difference here is that the spaces are removed, so the result is an identifier rather than a title.

Common mistakes

  • Skipping toLowerCase(). Capitals in the input survive and you get TOTALFARE.
  • Capitalizing the first word too. That's PascalCase (TotalFare), a different style, used for class names.
  • Splitting on ' ' only. Hyphens, underscores and double spaces all slip through.

Try it yourself

  1. Write pascal(text) that capitalizes every word, including the first: 'bus stop' becomes 'BusStop'.
  2. Write snake(name) that turns 'totalFareInKobo' into 'total_fare_in_kobo'.
  3. Use camel to turn every key of { 'Bus Stop': 'Yaba', 'total fare': 500 } into camelCase.

Keep practising

Newsletter

New writing, when it lands.

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