trex005's answer was good, and trex005's addition to it was even more handy, but if you're going to go that far, why not go all the way and allow you to convert back and forth between dashed, underscore, camelCase AND UpperCamelCase as needed?
For those who'd rather not mess with natives:
formatParts = function(string){
var parts = [];
string.replace(/([_\-A-Z]|^[^_\-A-Z])([^_\-A-Z]*)/g,function($0,$1,$2){
var part = $1.match(/[_\-]/)?$2:$1+$2;
parts.push(part.toLowerCase());
});
return parts;
}
toCamelCase = function(string){
var output = '';
formatParts(string).forEach(function(part,index){
output += index?part.charAt(0).toUpperCase() + part.substring(1):part;
});
return output;
}
toUpperCamelCase = function(string){
var output = '';
formatParts(string).forEach(function(part,index){
output += part.charAt(0).toUpperCase() + part.substring(1);
});
return output;
}
toDashed = function(string){
return formatParts(string).join('-');
}
toUnderscored = function(string){
return formatParts(string).join('_');
}
Or for those comfortable extending natives:
if (!String.prototype.formatParts)String.prototype.formatParts = function(){
var parts = [];
this.replace(/([_\-A-Z]|^[^_\-A-Z])([^_\-A-Z]*)/g,function($0,$1,$2){
var part = $1.match(/[_\-]/)?$2:$1+$2;
parts.push(part.toLowerCase());
});
return parts;
}
if (!String.prototype.toCamelCase)String.prototype.toCamelCase = function(){
var output = '';
this.formatParts().forEach(function(part,index){
output += index?part.charAt(0).toUpperCase() + part.substring(1):part;
});
return output;
}
if (!String.prototype.toUpperCamelCase)String.prototype.toUpperCamelCase = function(){
var output = '';
this.formatParts().forEach(function(part,index){
output += part.charAt(0).toUpperCase() + part.substring(1);
});
return output;
}
if (!String.prototype.toDashed)String.prototype.toDashed = function(){
return this.formatParts().join('-');
}
if (!String.prototype.toUnderscored)String.prototype.toUnderscored = function(){
return this.formatParts().join('_');
}
Fiddle: http://jsfiddle.net/trex005/akj0hx7b/3/