Alex Rivera | Logout

Converting a string with spaces into camel case

Asked 2010-06-03T23:30:08.570
306

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.

Edit
Report

2 Answers

72

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.

answered 2010-06-03T23:46:31.290
0

Basic approach would be to split the string with a regex matching upper-case or spaces. Then you'd glue the pieces back together. Trick will be dealing with the various ways regex splits are broken/weird across browsers. There's a library or something that somebody wrote to fix those problems; I'll look for it.

here's the link: http://blog.stevenlevithan.com/archives/cross-browser-split

answered 2010-06-03T23:34:33.360

Your Answer