Convert string to camel case

JavaScript

function toCamelCase(str) {
  var firstWordCapital = str.charAt(0) == str.charAt(0).toUpperCase();
  var camelCase = "";

  str.split(/[- _]+/).forEach((word, wordIndex) => {
    word.split('').forEach((char, charIndex) => {
      if (wordIndex == 0 && charIndex == 0) {
        camelCase += firstWordCapital ? char.toUpperCase() : char.toLowerCase();
      } else {
        camelCase += charIndex == 0 ? char.toUpperCase() : char.toLowerCase();
      }
    });
  });

  return camelCase;
}

Tags

  1. javascript (Private)
  2. 6-kyu (Private)
  3. codewars (Private)
  4. answer (Private)