Explain Codes LogoExplain Codes Logo

Converting a string with spaces into camel case

javascript
string-manipulation
regex-patterns
camel-case-conversion
Nikita BarsukovbyNikita Barsukov·Oct 20, 2024
TLDR

Quiсkly convert a spaced string into camelCase using the replace() method along with a regular expression (regex):

const getCamelCase = s => s.toLowerCase() .replace(/[^a-z0-9](.)/g, (_, c) => c.toUpperCase()); // making the string dance(flip)! console.log(getCamelCase("string to camel case")); // outputs "stringToCamelCase"

This concise piece of code first converts the string to lowercase and then capitalizes all letters following non-alphanumeric characters to create a camelCased string.

Nailing the regex pattern

Regular expressions, or regex, are noteworthy for defining search patterns within text. They prove extremely handy with string manipulation tasks, such as switching strings to different case styles.

The regex pattern /[^a-z0-9](.)/g zeros in specifically on non-alphanumeric characters followed by any character and captures it for use in the replacement.

Dealing with edge cases

While solving common needs, you may face particular situations where the string supports multilingual characters, or you have to apply case conversion to more complicated strings containing a mix of letters, numbers, and symbols.

  • Make sure the regex takes into account Unicode characters when managing multilingual characters.
  • For strings starting with a space or special character, you may require to modify the function to get these out in the first place.

Cross-browser support

For all the gold regular expressions are worth, they can sometimes lead to cross-browser issues. Make sure your code still behaves in different environments or leverage polyfills to flatten out any discrepancies.

Adhering to camelCase conventions

After running the regex replacements, remember to keep the first character as lowercase to maintain perfect camelCase typing standards:

const toPerfectCamelCase = s => { let alteredString = s.toLowerCase() .replace(/[^a-z0-9](.)/g, (_, c) => c.toUpperCase()); // Do the flip! return alteredString.charAt(0).toLowerCase() + alteredString.slice(1); // Roll back the first flip! }; console.log(toPerfectCamelCase(" String to camel case")); // prints "stringToCamelCase"

Techniques and tools

Every JavaScript programmer has their unique style. There are other ways to achieve camelCase strings, here are two additional methods.

The lodash magic wand

Lodash, a JavaScript utility library, provides a ready-to-go function to deal with your camelCase needs:

const camelCaseStr = _.camelCase("string to camel case"); // lodash to the rescue! console.log(camelCaseStr); // "stringToCamelCase"

Check the lodash documentation to understand its various offerings in detail.

ES6 and functional programming love

Leveraging the new ES6 features, and functional programming methods, our camel case conversion can look something like this:

const transformToCamelCase = str => str .split(' ') .map((word, index) => index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join(''); // It's magic! But in a geeky way! console.log(transformToCamelCase("string to camel case")); // outputs "stringToCamelCase"

This approach simplifies the camelCasing process into a sequence of transformations which makes the code more understandable and easier to maintain.