How to Convert a String to CamelCase in JavaScript

Last updated on May 21, 2022
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.

11 Amazing New Features in ES13

11 Amazing New Features in ES13
Get up to speed with all the latest features added in ECMAScript 13 to modernize your JavaScript with shorter and more expressive code.

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

Every Crazy Thing JavaScript Does

Every Crazy Thing JavaScript Does
Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.

See also