Search code examples
javascriptregexcamelcasing

Converting a string with spaces into camel case


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.


Solution

  • I just ended up doing this:

    String.prototype.toCamelCase = function(str) {
        return str
            .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
            .replace(/\s/g, '')
            .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
    }
    

    I was trying to avoid chaining together multiple replace statements. Something where I'd have $1, $2, $3 in my function. But that type of grouping is hard to understand, and your mention about cross browser problems is something I never thought about as well.