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.

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
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also