How can I convert a string to camel case in JavaScript?
Richard W
richard w profile pic

To convert a string to camel case in JavaScript, you can follow these steps: 1. Remove any leading or trailing whitespace from the string. 2. Split the string into an array of words using a delimiter, such as space or underscore. 3. Convert all the words to lowercase, except the first word. 4. Capitalize the first letter of each word except the first word. 5. Join the words back together without any spaces or delimiters. Here's an example implementation of a function that converts a string to camel case:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

function toCamelCase(str) {
  // Remove leading and trailing whitespace
  str = str.trim();
  
  // Split the string into an array of words
  const words = str.split(/[\s_]+/);
  
  // Capitalize the first letter of each word except the first word
  const camelCaseWords = words.map((word, index) => {
    if (index === 0) {
      // Keep the first word as is
      return word.toLowerCase();
    } else {
      // Capitalize the first letter of the subsequent words
      return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
    }
  });
  
  // Join the words back together without spaces
  const camelCaseStr = camelCaseWords.join('');
  
  return camelCaseStr;
}

// Example usage
const inputString = 'hello world_example';
const camelCaseString = toCamelCase(inputString);
console.log(camelCaseString); // "helloWorldExample"

In this example, the functiontoCamelCase takes a string as input and performs the necessary steps to convert it to camel case. It uses regular expressions to split the string into words based on spaces or underscores. It then applies the appropriate transformations to each word and finally joins them back together without any spaces.