Converting any string into camel case

Scott Klarenbach picture Scott Klarenbach · Jun 4, 2010 · Viewed 317.4k times · Source

How can I convert a string into camel case using javascript regex?

EquipmentClass name or Equipment className or equipment class name or Equipment Class Name

should all become: equipmentClassName.

Answer

Christian C. Salvadó picture Christian C. Salvadó · Jun 4, 2010

Looking at your code, you can achieve it with only two replace calls:

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index === 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, '');
}

camelize("EquipmentClass name");
camelize("Equipment className");
camelize("equipment class name");
camelize("Equipment Class Name");
// all output "equipmentClassName"

Edit: Or in with a single replace call, capturing the white spaces also in the RegExp.

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
    if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
    return index === 0 ? match.toLowerCase() : match.toUpperCase();
  });
}