Converting a string to camelCase should be easy in Node.js or web environments using JavaScript. There are many ways to solve this problem, with and without external dependencies.
Kevin Peters
—
5/6/2021
There are many ways to achieve these things. We will look first at the no-dependency version and then present you many alternatives that are a lot better tested.
Dependencies are not often needed for a lot of use-cases. So let us explore options without external dependencies.
1const toCamelCase = text => {
2 return text
3 .replace(/(?:^\w|[A-Z]|\b\w)/g, (leftTrim, index) =>
4 index === 0 ? leftTrim.toLowerCase() : leftTrim.toUpperCase(),
5 )
6 .replace(/\s+/g, "");
7};
8
9// Usage
10toCamelCase("SomeClass name"); // => someClassName
11toCamelCase("some className"); // => someClassName
12toCamelCase("some class name"); // => someClassName
13toCamelCase("Some Class Name"); // => someClassName
14
This is probably the most most common technique top convert strings to camelCase. First a replace function is getting called on the string and splits the string first by the dividing characters and then uppercases the first character of each part except it is the first occurrence.
A small detail to remember is that the splitting function works for most white spaces but will not work on any other case like hyphens or different case types.
1export const toCamelCase = (text: string): string => {
2 return text
3 .replace(/(?:^\w|[A-Z]|\b\w)/g, (leftTrim: string, index: number) =>
4 index === 0 ? leftTrim.toLowerCase() : leftTrim.toUpperCase(),
5 )
6 .replace(/\s+/g, "");
7};
8
9// Usage
10toCamelCase("SomeClass name"); // => someClassName
11toCamelCase("some className"); // => someClassName
12toCamelCase("some class name"); // => someClassName
13toCamelCase("Some Class Name"); // => someClassName
14
The TypeScript example basically works the same as the example above. It splits the string and upppercases or lowercases the first character. But this time with type defintions!
Another alternative is to use a package that might be already in your codebase called lodash. Lodash is an utility library that mostly gets introduced because of its great array functionalities. But one functionality often overlooked is the ability to convert case types.
1const _ = require("lodash");
2
3_.camelCase("Foo Bar"); // => 'fooBar'
4_.camelCase("--foo-bar--"); // => 'fooBar'
5_.camelCase("__FOO_BAR__"); // => 'fooBar'
6
As you can see in the code example it is working flawless. It is well supported and supports a lot more case types than the solution above.
Another external package that you can use is change-case. change-case is written in TypeScript and only focuses on converting case types. It is a great utility package that is also used heavily by this website for conversions. In comparison to the lodash alternative it supports many more cases like:
So how can you use it?
1import { camelCase } from "change-case";
2
3camelCase("test string"); // => "testString"
4camelCase("test_string"); // => "testString"
5camelCase("TestString"); // => "testString"
6
Usability by this library is so easy and it does what it promises. It converts the string. Hooray!
If you are working in an older environment you also might need a version to convert to camelCase without fancy arrow functions and other ECMAScript 6+ features. For that we can use the version below.
1function formatCase(leftTrim, index) {
2 return index === 0 ? leftTrim.toLowerCase() : leftTrim.toUpperCase();
3}
4
5function toCamelCase(text) {
6 return text.replace(/(?:^\w|[A-Z]|\b\w)/g, formatCase).replace(/\s+/g, "");
7}
8
9// Usage
10toCamelCase("SomeClass name"); // => someClassName
11toCamelCase("some className"); // => someClassName
12toCamelCase("some class name"); // => someClassName
13toCamelCase("Some Class Name"); // => someClassName
14
Another use case that you might want to have a solution for is changing the keys of an object to camelCase. In the last blog article we explained in a short format on how to change any case of object properties in JavaScript.
It is actually quite easy to convert every object key. You just have to traverse every key in an object and map arrays when they occur. This should cover most of the standard use cases in the JavaScript and TypeScript world. So let us check how to do this.
1const { camelCase } = require("change-case");
2
3const isObject = o => {
4 return o === Object(o) && !Array.isArray(o) && typeof o !== "function";
5};
6
7const changeCase = entity => {
8 if (entity === null) return entity;
9
10 if (isObject(entity)) {
11 const changedObject = {};
12 Object.keys(entity).forEach(originalKey => {
13 const newKey = camelCase(originalKey);
14 changedObject[newKey] = changeCase(entity[originalKey]);
15 });
16 return changedObject;
17 } else if (Array.isArray(entity)) {
18 return entity.map(element => {
19 return changeCase(element);
20 });
21 }
22
23 return entity;
24};
25
26const sourceJson = '{"test_case":true}';
27const sourceObject = JSON.parse(sourceJson);
28
29const result = changeCase(sourceObject); // Will be { testCase: true }
30
As I said this will not cover special data structures like Maps, Sets and similar but will work for most common data structures. We have also decided to use change-case because it would help you to change the target case later on quite simply.
Ever struggled to generate URL slugs from a long list of words in Google Sheets or Microsoft Excel? Not with our guide. Learn how to write a custom function to change the case style to dash-case, also known as kebab- or hyphen-case.
Kevin Peters
—
6/3/2021
Converting a string to camelCase in JavaScript (JS) can be quite tricky with all edge cases. This blog will show you how to handle the edge cases and even converting object keys.
Kevin Peters
—
5/6/2021
Changing the keys in objects in JavaScript objects is sometimes required. JavaScript mostly works with camelCase and transforming other case types is really helpful to make linters happy.
Kevin Peters
—
4/11/2021
For the hyphen-separated case there are multiple names: kebab-case, hyphen-case, slug-case and many other options... But what is the right one to choose. This article will help you to make a decision.
Kevin Peters
—
3/17/2021
The reasons why we love our technology stack at caseconverter.pro are quite diverse. Read it here and gather insightful statistics about which technologies were used and why you should use them too.
Kevin Peters
—
1/19/2020