views:

274

answers:

4

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".

Thanks.

A: 

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

Pointy
+3  A: 

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.

Scott
That looks fine to me, and nothing looks suspicious as far as cross-browser issues. (Not that I'm a super-expert or anything.)
Pointy
+1  A: 

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(letter, index) {
    return index == 0 ? letter.toLowerCase() : letter.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();
  });
}
CMS
A: 

If regexp isn't required, you might want to look at following code I made a long time ago for Twinkle:

String.prototype.toUpperCaseFirstChar = function() {
    return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
}

String.prototype.toLowerCaseFirstChar = function() {
    return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 );
}

String.prototype.toUpperCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim );
}

String.prototype.toLowerCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim );
}

I haven't made any performance tests, and regexp versions might or might not be faster.

azatoth