How to Convert a String to CamelCase in JavaScript

In camelcase, the first word of the phrase is lowercased, and all the following words are uppercased. In this article, we’ll be looking at some simple ways to convert a JavaScript string to camelcase.

String Regex Replace

We can use the String replace method with regex matching to convert the string to camel case:

function camelize(str) {
  return str
    .replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) =>
      index === 0
        ? letter.toLowerCase()
        : letter.toUpperCase()
    .replace(/\s+/g, '');

camelize('first variable name'); // firstVariableName
camelize('FirstVariable Name'); // firstVariableName
camelize('FirstVariableName'); // firstVariableName

The first regular expression matches the first letter with ^\w and the first letter of every word with \b\w. It also matches any capital letter with [A-Z]. It lowercases the letter if it’s the first of the string and uppercases it if otherwise. After that, it removes any whitespace in the resulting word with \s+ in the second regex.

Lodash camelCase Method

We can also use the camelCase method from the lodash library to convert the string to camelcase. It works similarly to our camelize function above.

_.camelize('first variable name'); // firstVariableName
_.camelize('FirstVariable Name'); // firstVariableName
_.camelize('FirstVariableName'); // firstVariableName

11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *