How to Convert a String to Camel Case in JavaScript

08/02/2021

Contents

In this article, you will learn how to convert a string to camel case in JavaScript.

Converting a string to camel case in JavaScript

In JavaScript, you can convert a string to camel case using a variety of methods. Camel case is a naming convention where the first word is lowercase and subsequent words are capitalized.

Using a regular expression

One of the most common ways to convert a string to camel case in JavaScript is to use a regular expression to split the string at word boundaries and then capitalize the first letter of each word except for the first word.

Example

function toCamelCase(str) {
  return str.replace(/[-_](.)/g, function(match, group) {
    return group.toUpperCase();
  });
}

console.log(toCamelCase("hello-world")); // "helloWorld"
console.log(toCamelCase("hello_world")); // "helloWorld"
console.log(toCamelCase("hello-world-this-is-camel-case")); // "helloWorldThisIsCamelCase"

In this example, we defined a function called toCamelCase that takes a string as an argument and uses a regular expression to split the string at hyphens or underscores followed by a character, and then capitalize that character. The resulting string is returned as camel case.

Using string methods

You can also use built-in string methods to convert a string to camel case. This method involves splitting the string into an array of words, capitalizing the first letter of each word except for the first word, and then joining the array back into a string.

Example

function toCamelCase(str) {
  const words = str.split(/[-_]/);
  return words.reduce((result, word, index) => {
    if (index === 0) {
      return result + word;
    }
    return result + word.charAt(0).toUpperCase() + word.slice(1);
  }, '');
}

console.log(toCamelCase("hello-world")); // "helloWorld"
console.log(toCamelCase("hello_world")); // "helloWorld"
console.log(toCamelCase("hello-world-this-is-camel-case")); // "helloWorldThisIsCamelCase"

In this example, we defined a function called toCamelCase that takes a string as an argument and splits it into an array of words using a regular expression. We then use the reduce method to iterate over the array and capitalize the first letter of each word except for the first word. The resulting string is returned as camel case.

Using a third-party library

If you’re working with a large number of strings that need to be converted to camel case, you may want to consider using a third-party library such as Lodash. Lodash provides a camelCase method that converts a string to camel case.

Example

const _ = require('lodash');

console.log(_.camelCase("hello-world")); // "helloWorld"
console.log(_.camelCase("hello_world")); // "helloWorld"
console.log(_.camelCase("hello-world-this-is-camel-case")); // "helloWorldThisIsCamelCase"

In this example, we imported Lodash and used the camelCase method to convert a string to camel case.